[英]Complexity of deleting a key from python ordered dict
Deleting a key from a python dict
or defaultdict
in python is O(1) operation, as mentioned here and here . 在Python中删除python dict
或defaultdict
中的键是O(1)操作, 如此处和此处所述 。 To remove a key from OrderedDict
, we can either use del d[key]
or use popitem()
method, as mentioned in the docs . 要从OrderedDict
删除密钥,我们可以使用del d[key]
或使用popitem()
方法,如文档中所述 。
What is the underlying implementation of OrderedDict
and the time complexity of del
operation? OrderedDict
的底层实现和del
操作的时间复杂度是什么?
Edit: This answer OrderedDict performance (compared to deque) , refers to the complexity of del
in OrderedDict
as being O(1). 编辑:这个答案OrderedDict的性能(与deque相比) ,是指OrderedDict
中del
作为O(1)的复杂性。 However, how can we justify it at implementation detail level? 但是,我们如何在实施细节层面证明它的合理性呢?
The implementation of OrderedDict.__delitem__
in Python 3.7 is as follows: Python 3.7中OrderedDict.__delitem__
的实现如下:
def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which gets
# removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link = self.__map.pop(key)
link_prev = link.prev
link_next = link.next
link_prev.next = link_next
link_next.prev = link_prev
link.prev = None
link.next = None
This code does 3 things: 这段代码做了三件事:
Since all of the operations above take constant time, the complexity of OrderedDict.__delitem__
is constant as well. 由于上述所有操作都需要恒定的时间,因此OrderedDict.__delitem__
的复杂性也是不变的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.