本文翻译自 https://www.tutorialspoint.com/ordereddict-in-python
OrderedDict是Dict的一个子类,Dict与OrderedDict之间的唯一区别是:OrderedDict会根据插入的顺序来保存元素,而Dict可能保持这种顺序也可能不保持插入顺序。
要使用OrderedDict需要导入collections模块。
import collections
下面我们通过几个例子来看一下Dict和OrderedDict的区别。
我们通过给Dict和OrderedDict插入一些键和值来创建对象。我们可以看到在Dict中的顺序与插入的顺序是不同的。但是OrderedDict的顺序是固定的。
Example Code
import collections
#Create normal dict
my_dict = {}
my_dict['AA'] = 11
my_dict['BB'] = 22
my_dict['CC'] = 33
my_dict['DD'] = 44
for item in my_dict.items():
print(item)
print()
#Create ordered dict
my_ord_dict = collections.OrderedDict()
my_ord_dict['AA'] = 11
my_ord_dict['BB'] = 22
my_ord_dict['CC'] = 33
my_ord_dict['DD'] = 44
for item in my_ord_dict.items():
print(item)
Output:
('AA', 11)
('CC', 33)
('BB', 22)
('DD', 44)
('AA', 11)
('BB', 22)
('CC', 33)
('DD', 44)
当一个键的值被修改了,OrderedDict中键的顺序不会变化。但是Dict不能够保证键的顺序会不会变化。
Example Code
import collections
#Create normal dict
my_dict = {}
my_dict['AA'] = 11
my_dict['BB'] = 22
my_dict['CC'] = 33
my_dict['DD'] = 44
for item in my_dict.items():
print(item)
#Change the value for key BB
my_dict['BB'] = 100
print('After changing in Dict')
for item in my_dict.items():
print(item)
print()
#Create ordered dict
my_ord_dict = collections.OrderedDict()
my_ord_dict['AA'] = 11
my_ord_dict['BB'] = 22
my_ord_dict['CC'] = 33
my_ord_dict['DD'] = 44
for item in my_ord_dict.items():
print(item)
#Change the value for key BB
my_ord_dict['BB'] = 100
print('After changing in Ordered Dict')
for item in my_ord_dict.items():
print(item)
Output
('AA', 11)
('BB', 22)
('CC', 33)
('DD', 44)
After changing in Dict
('AA', 11)
('CC', 33)
('DD', 44)
('BB', 100)
('AA', 11)
('BB', 22)
('CC', 33)
('DD', 44)
After changing in Ordered Dict
('AA', 11)
('BB', 100)
('CC', 33)
('DD', 44)
当OrderedDict删除一个元素,然后再重新插入时,该元素会被放到OrderedDict的最后。虽然Orderedict是保持顺序的,但是当执行删除的时候对应的排序信息也丢失了,重新插入的时候当作一个新元素来处理。
Example Code
import collections
#Create ordered dict
my_ord_dict = collections.OrderedDict()
my_ord_dict['AA'] = 11
my_ord_dict['BB'] = 22
my_ord_dict['CC'] = 33
my_ord_dict['DD'] = 44
for item in my_ord_dict.items():
print(item)
#Delete item in key BB
my_ord_dict.pop('BB')
print('After Deleting')
for item in my_ord_dict.items():
print(item)
#re-inserting item
my_ord_dict['BB'] = 22
print('After Re-inserting')
for item in my_ord_dict.items():
print(item)
Output
('AA', 11)
('BB', 22)
('CC', 33)
('DD', 44)
After Deleting
('AA', 11)
('CC', 33)
('DD', 44)
After Re-inserting
('AA', 11)
('CC', 33)
('DD', 44)
('BB', 22)