【发布时间】:2021-10-26 12:52:06
【问题描述】:
dict 自 Python 3.6 以来一直保持插入顺序(请参阅this)。
OrderedDict 就是为此目的而开发的(在 Python 3.6 之前)。
自 Python 3.6 起,dict 或 OrderedDict 的键顺序是否始终相同?
我想知道我是否可以在我的代码中执行此操作并且始终具有相同的行为(除了相等性和OrderedDict 中的一些扩展方法)但更有效:
if sys.version_info[:2] >= (3, 6):
OrderedDict = dict
else:
from collections import OrderedDict
或者换个说法,对于 Python >=3.6,有什么理由使用OrderedDict?
【问题讨论】:
-
OrderedDict 具有 dict 中不存在的方法
-
为什么要这样做,而在较新的版本中也可以使用
from collections import OrderedDict? -
@Daweo:会快很多吧?
-
我认为实际的问题是为什么您首先要支持 Python 3.5 或更早版本。 The oldest version still maintained is Python 3.6,甚至这只是安全修复。
-
@Albert
OrderedDicthas a C implementation since Python 3.5,因此在许多操作上它应该与dict竞争。
标签: python