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?
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?
>>> l = [{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}]
>>> [tuple(d.values()) for d in l]
[(1, 'Foo'), (2, 'Bar')]
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]