字典中键的顺序 [英] The order of keys in dictionaries

查看:96
本文介绍了字典中键的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆