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

标签 python sorting dictionary

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

如果我有字典:

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 )。

关于python - 如何保持键/值与声明的顺序相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1867861/

相关文章:

python - 统计模型 : AttributeError: 'module' object has no attribute 'x13'

pandas - 如何按列表中的值对数据框进行排序

javascript - 从多个选项中获取所有变化

python - 动态创建嵌套字典

python - Pandas :nan->无

python - Python中的继承?

python - 通过 Paramiko SSH 的 SQLAlchemy

performance - 我们什么时候应该使用基数排序?

ios - 将循环中的对象从字典添加到数组

python - 如何使用字典中的键查找值