字典中键的顺序 [英] The order of keys in dictionaries
问题描述
代码:
d = {'a': 0, 'b': 1, 'c': 2}
l = d.keys()
print l
这将打印['a', 'c', 'b']
.我不确定方法keys()
如何确定 l 中关键字的顺序.但是,我希望能够以适当"的顺序检索关键字.当然,正确的顺序将创建列表['a', 'b', 'c']
.
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']
.
推荐答案
您可以使用 OrderedDict (需要Python 2.7)或更高版本.
You could use OrderedDict (requires Python 2.7) or higher.
此外,请注意,OrderedDict({'a': 1, 'b':2, 'c':3})
将不起作用,因为使用{...}
创建的dict
已经忘记了元素的顺序.而是要使用OrderedDict([('a', 1), ('b', 2), ('c', 3)])
.
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)])
.
如文档中所述,对于低于python 2.7的版本,您可以使用此食谱.
As mentioned in the documentation, for versions lower than Python 2.7, you can use this recipe.
这篇关于字典中键的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!