常规dict并不跟踪插入顺序,迭代处理会根据键在散列表中存储的顺序来生成值。在OrderDict中则相反,它会记住元素插入的顺序,并在创建迭代器时使用这个顺序。
import collections print 'Regular dictionary:'d = {} d['a'] = 'A'd['b'] = 'B'd['c'] = 'C'for k, v in d.items(): print k, v print '\nOrderDict:'d = collections.OrderedDict() d['a'] = 'A'd['b'] = 'B'd['c'] = 'C'for k, v in d.items(): print k, v
输出:
Regular dictionary: a A c C b B OrderDict: a A b B c C