orderdDict是对字典类型的补充,他记住了字典元素添加的顺序
注意:字典默认循环只输出key
1 import collections 2 dic = collections.OrderedDict() 3 dic["k1"] = "v1" 4 dic["k2"] = "v2" 5 dic["k3"] = "v3" 6 print(dic) 7 #实现原理:相当于用列表(有序)来维护字典(无序)排序,以下仅供理解 8 # dic = {"k1":"v1","k2":"v2"} 9 # li = ["k1","k2"] 10 # for i in li: 11 # print(dic.get(i)) 12 13 执行结果:无论执行多少次结果一样 14 OrderedDict([(‘k1‘, ‘v1‘), (‘k2‘, ‘v2‘), (‘k3‘, ‘v3‘)])
1 def popitem(self, last=True): 2 ‘‘‘od.popitem() -> (k, v), return and remove a (key, value) pair. 3 Pairs are returned in LIFO order if last is true or FIFO order if false.
1 #有序删除和指定删除 2 import collections 3 dic = collections.OrderedDict() 4 dic["k1"] = "v1" 5 dic["k2"] = "v2" 6 dic["k3"] = "v3" 7 print(dic) 8 dic.popitem() #有序拿掉,每次拿掉最后一个,相当于内存的栈存放,后进先出原则,而pop()就是强制拿出指定的值 9 print(dic) 10 11 执行结果: 12 OrderedDict([(‘k1‘, ‘v1‘), (‘k2‘, ‘v2‘), (‘k3‘, ‘v3‘)]) 13 OrderedDict([(‘k1‘, ‘v1‘), (‘k2‘, ‘v2‘)])
1 def move_to_end(self, key, last=True): 2 ‘‘‘Move an existing element to the end (or beginning if last==False). 3 4 Raises KeyError if the element does not exist. 5 When last=True, acts like a fast version of self[key]=self.pop(key).
1 #把指定键值移到最后 2 import collections 3 dic = collections.OrderedDict() 4 dic["k1"] = "v1" 5 dic["k2"] = "v2" 6 dic["k3"] = "v3" 7 print(dic) 8 dic.move_to_end("k1") #把指定键值移到最后 9 print(dic) 10 11 #执行结果: 12 OrderedDict([(‘k1‘, ‘v1‘), (‘k2‘, ‘v2‘), (‘k3‘, ‘v3‘)]) 13 OrderedDict([(‘k2‘, ‘v2‘), (‘k3‘, ‘v3‘), (‘k1‘, ‘v1‘)])
1 def setdefault(self, key, default=None): 2 ‘od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od‘ 3 if key in self: 4 return self[key] 5 self[key] = default 6 return default
1 #添加默认键 2 import collections 3 dic = collections.OrderedDict() 4 dic["k1"] = "v1" 5 dic["k2"] = "v2" 6 dic["k3"] = "v3" 7 print(dic) 8 dic.setdefault("k4","v4") #默认键值为None,不过可以添加值 9 print(dic) 10 11 #执行结果: 12 OrderedDict([(‘k1‘, ‘v1‘), (‘k2‘, ‘v2‘), (‘k3‘, ‘v3‘)]) 13 OrderedDict([(‘k1‘, ‘v1‘), (‘k2‘, ‘v2‘), (‘k3‘, ‘v3‘), (‘k4‘, ‘v4‘)])
时间: 2024-11-01 10:27:11