首页 > 解决方案 > Python中的dict()实际上是否像集合模块中的OrderedDict()一样排序

问题描述

引用python文档我有:

在 3.7 版更改: 字典顺序保证为插入顺序。这种行为是 CPython 3.6 的实现细节。

上述文档的链接

但是下面的代码让我觉得它不是有序的:

from collections import OrderedDict
d1 = dict()
d2 = dict()
d1['a'] = 1
d1['b'] = 2
d2['b'] = 2
d2['a'] = 1
print(d1 == d2)


d3 = OrderedDict()
d4 = OrderedDict()
d3['a'] = 1
d3['b'] = 2
d4['b'] = 2
d4['a'] = 1
print(d3 == d4)

上面的代码生成输出(对于 python 3.7.5):

True
False

本质上 dict() 应该显示与集合模块中的 OrderedDict() 相同的行为,但事实并非如此。请详细说明。

标签: pythonpython-3.x

解决方案


推荐阅读