【发布时间】:2014-10-18 06:14:22
【问题描述】:
初始化有序字典 (OD) 以使其保留初始数据的顺序的正确方法是什么?
from collections import OrderedDict
# Obviously wrong because regular dict loses order
d = OrderedDict({'b':2, 'a':1})
# An OD is represented by a list of tuples, so would this work?
d = OrderedDict([('b',2), ('a', 1)])
# What about using a list comprehension, will 'd' preserve the order of 'l'
l = ['b', 'a', 'c', 'aa']
d = OrderedDict([(i,i) for i in l])
问题:
OrderedDict是否会保留初始化时传递的元组列表或元组元组或列表元组或列表列表等的顺序(上面的第二个和第三个示例)?如何验证
OrderedDict是否真的维持订单?由于dict具有不可预测的顺序,如果我的测试向量幸运地具有与dict 的不可预测顺序相同的初始顺序怎么办?例如,如果我写的是d = OrderedDict({'a':1, 'b':2})而不是d = OrderedDict({'b':2, 'a':1}),我会错误地得出订单被保留的结论。在这种情况下,我发现dict是按字母顺序排列的,但这可能并不总是正确的。什么是使用反例来验证数据结构是否保持顺序的可靠方法,而不是反复尝试测试向量直到中断?
附:我将这里留给reference:“OrderedDict 构造函数和 update() 方法都接受关键字参数,但它们的顺序丢失了,因为 Python 的函数调用语义使用常规无序字典传入关键字参数”
P.P.S :希望将来 OrderedDict 也能保留 kwargs 的顺序(示例 1):http://bugs.python.org/issue16991
【问题讨论】:
-
具有讽刺意味的是,使用(非空)dict 初始化 OrderedDict 是 错误 的事情......可以说这应该导致警告,因为它可能违反用户的意图。
-
python3.6之后,
OrderDict(b=2, a=1)也是有道的。见PEP 468。
标签: python sorting dictionary ordereddictionary