有序字典

import collections
dic1=collections.OrderedDict()
dic3=collections.OrderedDict()
dic1 ={
'#1':{'cpu':1, 'diskhard':3,'neicun':5},
'#2':{'cpu':2, 'diskhard':3,'neicun':5},
'#3':{'cpu':1, 'diskhard':4,'neicun':5},
}
dic2 ={
'#1':{'cpu':1, 'diskhard':3,'neicun':5},
'#3':{'cpu':1, 'diskhard':3,'neicun':5},
'#4':{'cpu':2, 'diskhard':3,'neicun':6},
}
dic3['#1']={'cpu':1, 'diskhard':3,'neicun':5}
dic3['#2']={'cpu':1, 'diskhard':4,'neicun':5}
dic3['#3']={'cpu':2, 'diskhard':3,'neicun':5}
"""
如上图所示,dic1依然不会创造一个有序的字典,dic3会是一个有序字典
"""
dic3.move_to_end('#1')
print(dic3)
dic3.pop("#3")
'''pop并不按照顺序来'''
print(dic1)
print(dic2)
print(dic3)
dic3.setdefault("k4",66)
print(dic3)
dic3.update({"k1":22,'k8':45})
print(dic3)




输出结果

OrderedDict([('#2', {'cpu': 1, 'diskhard': 4, 'neicun': 5}), ('#3', {'cpu': 2, 'diskhard': 3, 'neicun': 5}), ('#1', {'cpu': 1, 'diskhard': 3, 'neicun': 5})])
{'#3': {'cpu': 1, 'diskhard': 4, 'neicun': 5}, '#1': {'cpu': 1, 'diskhard': 3, 'neicun': 5}, '#2': {'cpu': 2, 'diskhard': 3, 'neicun': 5}}
{'#3': {'cpu': 1, 'diskhard': 3, 'neicun': 5}, '#1': {'cpu': 1, 'diskhard': 3, 'neicun': 5}, '#4': {'cpu': 2, 'diskhard': 3, 'neicun': 6}}
OrderedDict([('#2', {'cpu': 1, 'diskhard': 4, 'neicun': 5}), ('#1', {'cpu': 1, 'diskhard': 3, 'neicun': 5})])
OrderedDict([('#2', {'cpu': 1, 'diskhard': 4, 'neicun': 5}), ('#1', {'cpu': 1, 'diskhard': 3, 'neicun': 5}), ('k4', 66)])
OrderedDict([('#2', {'cpu': 1, 'diskhard': 4, 'neicun': 5}), ('#1', {'cpu': 1, 'diskhard': 3, 'neicun': 5}), ('k4', 66), ('k1', 22), ('k8', 45)])

你可能感兴趣的:(有序字典)