这也导致一些同学在刚刚编写代码时感到困惑:
为什么字典的结果不按照我想要的顺序来?
好在 Python 里提供了一个解决方案:OrderedDict
在官方文档中,可以找到如下描述:
Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.
简单来说,就是有序字典和普通的字典并无差异,但是它记录了条目添加的顺序,当迭代有序字典时,字典内容随着被添加的顺序返回。
如果你在 python shell 中输入:
>>> from collections import OrderedDict
>>> help(OrderDict)
可以看到第一行写着:
class OrderedDict(__builtin__.dict)
也就是说,OrderedDict 是 dict 的子类。所以你可以放心地像 dict 一样来使用它。而同时,它又增加了对添加顺序的记录:
from collections import OrderedDict
d = OrderedDict()
d['c'] = 3
d['b'] = 2
d['a'] = 1
print(d)