Python collections模块中的 OrderedDict
引言
我们都知道,Python 中的 Dict 字典对象是无序的,但是无序的字典在有些时候会给我们的数据操作增加困难,此时,我们可以使用 OrderedDict,该字典类型的特点是它会按照插入顺序保留键值对的顺序。
正文
创建 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