该类型存放顺序和添加顺序一致,比如逐个赋值,但和dict直接转化过去的顺序不一定一样.
d1 = collections.OrderedDict()
d1['b'] = 'B'
d1['a'] = 'A'
d1['c'] = 'C'
d1['2'] = '2'
d1['1'] = '1'
# OrderedDict([('b', 'B'), ('a', 'A'), ('c', 'C'), ('2', '2'), ('1', '1')])
1 dict1 = {"1": 1, "2":2, '3':3} 2 print(dict1) 3 od1 = OrderedDict(dict1) # 和dict1初始化时看到的顺序不一定一样,但和dict1打印出来的顺序一致 4 print(od1) 5 6 #{'3': 3, '2': 2, '1': 1} 7 #OrderedDict([('3', 3), ('2', 2), ('1', 1)])
将OrderedDict转化为dict:
list_key = [] list_value = [] # OrderedDict转成dict for key in od1.keys(): list_key.append(key) for value in od1.values(): list_value.append(value) zip_od = zip(list_key, list_value) dict_od = dict(zip_od) print(dict_od)
对该类型可以进行排序操作.
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 #输出 OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]) OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
下面这种排序效果起不到作用:
sorted_od = (sorted(d1, key=lambda t: t[0])) #['1', '2', 'a', 'b', 'c'] 因为: for i in d1: print(i) # b # a # c # 2 # 1 for j in d1.items(): print(j) # ('b', 'B') # ('a', 'A') # ('c', 'C') # ('2', '2') # ('1', '1')