Code:
d = {'a': 0, 'b': 1, 'c': 2}
l = d.keys()
print l
这打印['a', 'c', 'b']
。我不确定该方法如何keys()
确定其中关键字的顺序l
。但是,我希望能够以“正确”的顺序检索关键字。
正确的顺序当然会创建列表['a', 'b', 'c']
.
Python 3.7+
在Python中3.7.0 https://docs.python.org/3.7/whatsnew/3.7.html插入顺序保存性质dict https://docs.python.org/3/library/stdtypes.html#mapping-types-dict物体已宣布 https://mail.python.org/pipermail/python-dev/2017-December/151283.html成为 Python 语言规范的正式部分。因此,您可以依赖它。
Python 3.6(CPython)
从 Python 3.6 开始,对于 Python 的 CPython 实现,字典维持插入顺序 https://docs.python.org/3.6/whatsnew/3.6.html#new-dict-implementation默认情况下。但这被认为是一个实现细节;你仍然应该使用collections.OrderedDict https://docs.python.org/3/library/collections.html#collections.OrderedDict如果您想要在其他 Python 实现中保证插入顺序。
Python >=2.7 和
Use the collections.OrderedDict https://docs.python.org/3/library/collections.html#collections.OrderedDict当你需要上课时dict
那
记住插入项目的顺序。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)