MCPcopy Index your code
hub / github.com/RustPython/RustPython / OrderedDict

Class OrderedDict

Lib/collections/__init__.py:90–343  ·  view source on GitHub ↗

Dictionary that remembers insertion order

Source from the content-addressed store, hash-verified

88 __slots__ = 'prev', 'next', 'key', '__weakref__'
89
90class OrderedDict(dict):
91 'Dictionary that remembers insertion order'
92 # An inherited dict maps keys to values.
93 # The inherited dict provides __getitem__, __len__, __contains__, and get.
94 # The remaining methods are order-aware.
95 # Big-O running times for all methods are the same as regular dictionaries.
96
97 # The internal self.__map dict maps keys to links in a doubly linked list.
98 # The circular doubly linked list starts and ends with a sentinel element.
99 # The sentinel element never gets deleted (this simplifies the algorithm).
100 # The sentinel is in self.__hardroot with a weakref proxy in self.__root.
101 # The prev links are weakref proxies (to prevent circular references).
102 # Individual links are kept alive by the hard reference in self.__map.
103 # Those hard references disappear when a key is deleted from an OrderedDict.
104
105 def __new__(cls, /, *args, **kwds):
106 "Create the ordered dict object and set up the underlying structures."
107 self = dict.__new__(cls)
108 self.__hardroot = _Link()
109 self.__root = root = _proxy(self.__hardroot)
110 root.prev = root.next = root
111 self.__map = {}
112 return self
113
114 def __init__(self, other=(), /, **kwds):
115 '''Initialize an ordered dictionary. The signature is the same as
116 regular dictionaries. Keyword argument order is preserved.
117 '''
118 self.__update(other, **kwds)
119
120 def __setitem__(self, key, value,
121 dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
122 'od.__setitem__(i, y) <==> od[i]=y'
123 # Setting a new item creates a new link at the end of the linked list,
124 # and the inherited dictionary is updated with the new key/value pair.
125 if key not in self:
126 self.__map[key] = link = Link()
127 root = self.__root
128 last = root.prev
129 link.prev, link.next, link.key = last, root, key
130 last.next = link
131 root.prev = proxy(link)
132 dict_setitem(self, key, value)
133
134 def __delitem__(self, key, dict_delitem=dict.__delitem__):
135 'od.__delitem__(y) <==> del od[y]'
136 # Deleting an existing item uses self.__map to find the link which gets
137 # removed by updating the links in the predecessor and successor nodes.
138 dict_delitem(self, key)
139 link = self.__map.pop(key)
140 link_prev = link.prev
141 link_next = link.next
142 link_prev.next = link_next
143 link_next.prev = link_prev
144 link.prev = None
145 link.next = None
146
147 def __iter__(self):

Calls

no outgoing calls