Python旧版本的OrderedDict

2024-04-20 13:37:33 发布

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

有序字典是非常有用的结构,但不幸的是,它们是最近才在3.12.7版本中使用的。如何在旧版本中使用有序词典?


Tags: 版本字典结构词典有序
3条回答

我用pip在python 2.6上安装了ordereddict

pip install ordereddict

根据documentation,对于Python版本2.4或更高版本,应该使用this code。还有一些code from Raymond Hettinger,是PEP的贡献者之一。这里的代码声称在2.6和3.0下工作,是为提案而制定的。

要为不同版本的Python导入OrderedDict类,请考虑以下代码片段:

try:
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict

# Now use it from any version of Python
mydict = OrderedDict()

Python 2.6之前的版本需要安装ordereddict(使用pip或其他方法),但较新的版本将从内置的collections模块导入。

相关问题 更多 >