我们都知道,Python 中的 Dict 字典对象是无序的,但是无序的字典在有些时候会给我们的数据操作增加困难,此时,我们可以使用 OrderedDict,该字典类型的特点是它会按照插入顺序保留键值对的顺序。
from collections import OrderedDict
ordered_dict = OrderedDict()
ordered_dict['a'] = 1
ordered_dict['b'] = 2
ordered_dict['c'] = 3
print(ordered_dict) # OrderedDict([('a', 1), ('b', 2), ('c', 3)])
from collections import OrderedDict
ordered_dict = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
ordered_dict.pop('a')
ordered_dict['a'] = 1
print(ordered_dict) # OrderedDict([('b', 2), ('c', 3), ('a', 1)])
可以看到,此时 ‘a’:1 键值对的位置到了第三个。
对于 Python 3.7+ 的版本,普通 dict 也会保留键值对插入的顺序。但是 OrderedDict 有一些其他的功能是普通 dict 不具备的。
from collections import OrderedDict
ordered_dict = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
ordered_dict.move_to_end('a')
print(ordered_dict) # OrderedDict([('b', 2), ('c', 3), ('a', 1)])
from collections import OrderedDict
ordered_dict = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
ordered_dict.move_to_end('c', last=False)
print(ordered_dict) # OrderedDict([('c', 3), ('a', 1), ('b', 2)])
from collections import OrderedDict
# 普通字典
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 2, 'a': 1}
print(dict1 == dict2) # True
# ordered_dict
ordered_dict1 = OrderedDict([('a', 1), ('b', 2)])
ordered_dict2 = OrderedDict([('b', 2), ('a', 1)])
print(ordered_dict1 == ordered_dict2) # False
from collections import OrderedDict
ordered_dict = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
item = ordered_dict.popitem()
print(ordered_dict) # OrderedDict([('a', 1), ('b', 2)])
print(item) # ('c', 3)
from collections import OrderedDict
ordered_dict = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
item = ordered_dict.popitem(last=False)
print(ordered_dict) # OrderedDict([('b', 2), ('c', 3)])
print(item) # ('a', 1)
from collections import OrderedDict
ordered_dict = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
for key, value in reversed(ordered_dict.items()):
print(key, value)
"""
c 3
b 2
a 1
"""
如果大家觉得有用,就点个赞让更多的人看到吧~