Python_使用OrderedDict可以对python2的dict类型排序
分别在python2和python3中,执行下面代码
a = {"a": 1, "b": 2, "c": 3} print(a)
python2执行结果
python3执行结果
从上面结果可以看出
在python3中,dict类型是有序的
在python2中,dict类型是无序的。在python2如果需要对dict类型排序,需要使用collections模块的OrderedDict
请看下面的实例:
# coding: utf-8 from collections import OrderedDict # 注意:不能直接把整个dict放进去,这样做还是无序的 d = OrderedDict() d.update({"a": 1, "b": 2, "c": 3}) print(d) # 只能按顺序逐个添加 d1 = OrderedDict() d1.update({"a": 1}) d1.update({"b": 2}) d1.update({"c": 3}) print(d1)