python - 如何保持键/值与声明的顺序相同?

我有一本按特定顺序声明的字典,并希望始终保持该顺序。键/值不能真正根据它们的值保持顺序,我只希望它按照我声明的顺序。

如果我有字典:

d = {'ac': 33, 'gw': 20, 'ap': 102, 'za': 321, 'bs': 10}

如果我查看或遍历它,它的顺序不是这样,有什么方法可以确保 Python 保持我在其中声明键/值的显式顺序?

最佳答案

从 Python 3.6 开始,标准的 dict 类型默认保持插入顺序。

定义

d = {'ac':33, 'gw':20, 'ap':102, 'za':321, 'bs':10}

将生成一个字典,其中的键按源代码中列出的顺序排列。

这是通过对稀疏哈希表使用带有整数的简单数组来实现的,其中这些整数索引到另一个存储键值对(加上计算的哈希)的数组中。后一个数组恰好按插入顺序存储项目,整个组合实际上使用的内存比 Python 3.5 和之前使用的实现要少。见 original idea post by Raymond Hettinger了解详情。

在 3.6 中,这仍被视为实现细节;见What's New in Python 3.6 documentation :

The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).

Python 3.7 将此实现细节提升为 语言规范,因此现在强制 dict 在与该版本或更高版本兼容的所有 Python 实现中保持顺序。见 pronouncement by the BDFL .从 Python 3.8 开始,字典也支持 iteration in reverse .

您可能仍想使用 collections.OrderedDict() class在某些情况下,因为它在标准 dict 类型之上提供了一些附加功能。如为reversible (这延伸到 view objects ),并支持重新排序(通过 move_to_end() method )。

https://stackoverflow.com/questions/1867861/

相关文章:

python - 如何将本地时间字符串转换为 UTC?

python - python中的链式调用父初始化器

python - 如何使用 Python 重命名文件

python - 为什么访问全局变量不需要 'global' 关键字?

python - 漂亮地打印一个没有科学记数法和给定精度的 NumPy 数组

python - 在 Python 中打印多个参数

python - pandas:使用运算符链接过滤 DataFrame 的行

python - 为什么使用 argparse 而不是 optparse?

python - 动态打印一行

python - python中dict的深拷贝