【发布时间】:2011-03-13 05:44:22
【问题描述】:
我有一个字典列表,如下所示:
[{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}]
我想将每个字典中的值转换成这样的元组列表:
[(1,'Foo'),(2,'Bar')]
我该怎么做?
【问题讨论】:
标签: python dictionary tuples
我有一个字典列表,如下所示:
[{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}]
我想将每个字典中的值转换成这样的元组列表:
[(1,'Foo'),(2,'Bar')]
我该怎么做?
【问题讨论】:
标签: python dictionary tuples
>>> l = [{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}]
>>> [tuple(d.values()) for d in l]
[(1, 'Foo'), (2, 'Bar')]
【讨论】:
id 总是在name 之前出现,尤其是在不同的版本/实现中。例如,在 IronPython(例如 trypython.org)中输入上述示例当前会给出[('Foo', 1), ('Bar', 2)]。你甚至不能确定两个具有相同键的字典会以相同的顺序给出它们的keys()(它们会用于像这样的简单情况,但这是你不应该依赖的实现细节)。跨度>
Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end. link
请注意,SilentGhost 答案中的方法不能保证每个元组的顺序,因为字典及其 values() 没有固有顺序。因此,在一般情况下,您可能会得到('Foo', 1) 和(1, 'Foo')。
如果这是不可接受的,并且您肯定首先需要 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])
【讨论】: