print 'Regular dictionary:' d2={} d2['a']='A' d2['b']='B' d2['c']='C' d3={} d3['c']='C' d3['a']='A' d3['b']='B' print d2==d3 print 'OrderedDict:' d4=collections.OrderedDict() d4['a']='A' d4['b']='B' d4['c']='C' d5=collections.OrderedDict() d5['c']='C' d5['a']='A' d5['b']='B' print d4==d5 输出: Regular dictionary: True OrderedDict: False
dd = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2} #按key排序 kd = collections.OrderedDict(sorted(dd.items(), key=lambda t: t[0])) print(kd) #按照value排序 vd = collections.OrderedDict(sorted(dd.items(),key=lambda t:t[1])) print(vd)
Regular dictionary:
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])