其实很简单OrderedDict
是Python中一个字典dict
的变体,它可以按照元素添加的顺序来保持键值对(key-value pair)的顺序。与普通的字典相比,OrderedDict 保持了元素的添加顺序。这在需要按照添加的顺序访问键值对时非常有用。
from collections import OrderedDict
# 创建一个空的 OrderedDict
ordered_dict = OrderedDict()
# 添加键值对
ordered_dict['one'] = 1
ordered_dict['two'] = 2
ordered_dict['three'] = 3
normal_dict = {}
normal_dict['one'] = 1
normal_dict['two'] = 2
normal_dict['three'] = 3
print(ordered_dict)
print(normal_dict)
# 遍历 OrderedDict 的键值对(按照添加的顺序)
for key, value in ordered_dict.items():
print(key, value)
for key, value in normal_dict.items():
print(key, value)
结果如下
OrderedDict([('one', 1), ('two', 2), ('three', 3)])
{'one': 1, 'two': 2, 'three': 3}
one 1
two 2
three 3
one 1
two 2
three 3