views:

77

answers:

2

I have a list of dictionaries that looks like this:

[{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}]

I'd like to convert the values from each dict into a list of tuples like this:

[(1,'Foo'),(2,'Bar')]

How can I do this?

+7  A: 
>>> l = [{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}]
>>> [tuple(d.values()) for d in l]
[(1, 'Foo'), (2, 'Bar')]
SilentGhost
simple and exactly what it says on the tin, thanks very much
chrism
and probably wrong. see answer below.
Marco Mariani
@Marco: it gives consistent order for given keys, there is nothing wrong about this answer.
SilentGhost
You can't guarantee `id` will always come out before `name`, especially across different versions/implementations. For example entering the above example in IronPython (eg. trypython.org) currently gives `[('Foo', 1), ('Bar', 2)]`. You can't even be sure that two dicts with the same keys will give their `keys()` in the same order (they will for simple cases like this, but that's an implementation detail you're not supposed to rely on).
bobince
+5  A: 

Note that the approach in SilentGhost's answer doesn't guarantee the order of each tuple, since dictionaries and their values() have no inherent order. So you might just as well get ('Foo', 1) as (1, 'Foo'), in the general case.

If that's not acceptable and you definitely need the id first, you'll have to do that explicitly:

[(d['id'], d['name']) for d in l]
bobince
+1 dictionary ordering is not specified.
Daren Thomas