Python中的OrderedDict
OrderedDict是Python中dict对象的子类。OrderedDict和dict之间的唯一区别是,在OrderedDict中,它保持插入键的顺序。在字典中,排序可能会或可能不会发生。
OrderedDict是一个标准的库类,它位于collections模块中。
首先要使用它,我们需要将其导入集合标准库模块。
import collections
在本节中,我们将看到一些关于OrderedDict的操作以及OrderedDict和Dict之间的区别。
我们可以在Dict和OrderedDict中放入一些键和值。在此示例中,我们可以看到Dict的顺序可能有所不同。但是对于OrderedDict。它将被修复。
范例程式码
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)
输出结果
('AA', 11) ('CC', 33) ('BB', 22) ('DD', 44) ('AA', 11) ('BB', 22) ('CC', 33) ('DD', 44)
更改指定键的值
当指定键的值更改时,对于OrderedDict,键的顺序将不会更改。我们可以看到该语句对于Dict类型对象可能正确,也可能不正确。
范例程式码
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)
输出结果
('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中删除一个元素并对该键和值执行重新插入操作时,它将把它推回到后面。尽管它在插入时保持顺序,但是为了删除,它会删除订购信息,并作为重新插入的新条目。
范例程式码
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)
输出结果
('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)