图片截取自 Python 核心开发者 Raymond Hettinger 在 Youtube 上的一个视频 Modern Dictionaries by Raymond Hettinger 。Raymond 也是 Python 3.6 中 new dict 的提议者和发起者。
可以看到,Python 3.6 之前,字典都是无序存储的,但到了 Python 3.6,就变成了有序的。
如果想要在代码中保证字典有序,尤其是涉及到其他版本的 Python 实现的时候,还是得用 OrderedDict。
from collections import OrderedDict
xxoo = OrderedDict()
xxoo['a'] = 1
xxoo['b'] = 2
xxoo['c'] = 3
for i,j in xxoo.items():
print ('{} --> {}'.format(i,j))