Python converting the values from dicts into a tuples
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 f开发者_如何学Gorom 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]
This will convert the dictionary to tuple always in defined order
d = {'x': 1 , 'y':2}
order = ['y','x']
tuple([d[field] for field in order])
精彩评论