collections.OrderedDict

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

常规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 

 

 

转载于:https://my.oschina.net/xiaohuangsh/blog/1036440

你可能感兴趣的:(collections.OrderedDict)