Python字典中的关键顺序 [英] Key Order in Python Dictionaries
问题描述
代码:
d = {'a':0,'b':1,'c':2}
l = d.keys()
打印l
打印['a','c','b']。我不确定方法键如何确定 l 中关键字的顺序。但是,我希望能够以正确的顺序撤回关键字。当然这样做的顺序就是创建列表['a','b','c']。
使用 OrderedDict (需要Python 2.7)或更高版本。
另外,请注意 OrderedDict({'a':1,'b':2,'c':3})
dict
您创建的 {...}
已经忘记了元素的顺序。相反,您要使用 OrderedDict([('a',1),('b',2),('c',3)])
p>
如文档中所述,对于低于Python 2.7的版本,您可以使用这个食谱。
Code:
d = {'a': 0, 'b': 1, 'c': 2}
l = d.keys()
print l
This prints ['a', 'c', 'b']. I'm unsure of how the method keys determines the order of the keywords within l. However, I'd like to be able to retrive the keywords in the "proper" order. The proper order of course would create the list ['a', 'b', 'c'].
You could use OrderedDict (requires Python 2.7) or higher.
Also, note that OrderedDict({'a': 1, 'b':2, 'c':3})
won't work since the dict
you create with {...}
has already forgotten the order of the elements. Instead, you want to use OrderedDict([('a', 1), ('b', 2), ('c', 3)])
.
As mentioned in the documentation, for versions lower than Python 2.7, you can use this recipe.
这篇关于Python字典中的关键顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!