[英]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 from each dict into a list of tuples like this: 我想将每个dict的值转换为这样的元组列表:
[(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. 请注意,SilentGhost的答案中的方法并不能保证每个元组的顺序,因为字典及其
values()
没有固有的顺序。 So you might just as well get ('Foo', 1)
as (1, 'Foo')
, in the general case. 因此,在一般情况下,你也可以将
('Foo', 1)
(1, 'Foo')
。
If that's not acceptable and you definitely need the id
first, you'll have to do that explicitly: 如果这是不可接受的,你肯定首先需要
id
,你必须明确地这样做:
[(d['id'], d['name']) for d in l]
这将始终按定义的order
将字典转换为元组
d = {'x': 1 , 'y':2} order = ['y','x'] tuple([d[field] for field in order])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.