如何保持键/值按照声明的顺序相同?

2024-03-29 05:03:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本按特定顺序申报的词典,想一直按这个顺序保存。键/值实际上不能根据它们的值保持顺序,我只希望它按照我声明的顺序。

如果我有字典:

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

如果我查看或遍历它,它不是按这个顺序排列的,有没有办法确保Python将保持我在中声明键/值的显式顺序?


Tags: 声明字典bs顺序ac词典apgw
3条回答

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

定义

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

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

这是通过在稀疏散列表中使用一个带有整数的简单数组来实现的,其中这些整数索引到另一个存储键值对(加上计算出的散列)的数组中。后一个数组恰好按插入顺序存储项,而整个组合实际使用的内存比Python3.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

在某些情况下,您可能仍然希望使用^{} class,因为它在标准dict类型的基础上提供了一些附加功能。例如成为reversible(这扩展到view objects),支持重新排序(通过^{} method)。

我将举一个简单的例子,而不是解释理论部分。

>>> from collections import OrderedDict
>>> my_dictionary=OrderedDict()
>>> my_dictionary['foo']=3
>>> my_dictionary['aol']=1
>>> my_dictionary
OrderedDict([('foo', 3), ('aol', 1)])
>>> dict(my_dictionary)
{'foo': 3, 'aol': 1}
from collections import OrderedDict
OrderedDict((word, True) for word in words)

包含

OrderedDict([('He', True), ('will', True), ('be', True), ('the', True), ('winner', True)])

如果值是True(或任何其他不可变对象),也可以使用:

OrderedDict.fromkeys(words, True)

相关问题 更多 >