简体   繁体   English

从python有序字典中删除密钥的复杂性

[英]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 dictdefaultdict中的键是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相比) ,是指OrderedDictdel作为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: 这段代码做了三件事:

  • Remove an item from the internal key-value dictionary. 从内部键值字典中删除项目。
  • Remove a node from the dictionary holding linked list nodes. 从包含链接列表节点的字典中删除节点。
  • Delete an item from a doubly linked list. 从双向链接列表中删除项目。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM