python - 旧版本 Python 中字典中的键顺序

标签 python dictionary

代码:

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 dict 的插入顺序保存性质对象 has been declared成为 Python 语言规范的官方部分。因此,您可以依赖它。

Python 3.6 (CPython)

从 Python 3.6 开始,对于 Python 的 CPython 实现,字典 maintain insertion order默认。不过,这被认为是一个实现细节;你还是应该使用 collections.OrderedDict如果您希望在 Python 的其他实现中保证插入顺序。

Python >=2.7 和 <3.6

使用 collections.OrderedDict当你需要一个 dict 时的类 记住插入项目的顺序。

关于python - 旧版本 Python 中字典中的键顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5629023/

相关文章:

python - 什么是多维字典?

c# - 如何将 ConcurrentDictionary 转换为字典?

python - flask 和 Werkzeug : Testing a post request with custom headers

python - 停止 Pandas ExcelWriter() 创建额外的列

python - 我该如何解决以下SQL语法错误

python - Collections.Counter 如何实现快速排序?

python - 从键列表创建嵌套字典的方法

python - 如何在python中解密密码

python - 在Python中迭代HTML中的 "class"属性?

c++ - 错误 C2061 : syntax error : identifier 'map'