annotate OrderedDict.py @ 0:939c20789501 default tip

Uploaded
author rico
date Fri, 06 Apr 2012 10:51:28 -0400
parents
children
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
0
939c20789501 Uploaded
rico
parents:
diff changeset
1 # http://code.activestate.com/recipes/576693/
939c20789501 Uploaded
rico
parents:
diff changeset
2 # Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
939c20789501 Uploaded
rico
parents:
diff changeset
3 # Passes Python2.7's test suite and incorporates all the latest updates.
939c20789501 Uploaded
rico
parents:
diff changeset
4
939c20789501 Uploaded
rico
parents:
diff changeset
5 try:
939c20789501 Uploaded
rico
parents:
diff changeset
6 from thread import get_ident as _get_ident
939c20789501 Uploaded
rico
parents:
diff changeset
7 except ImportError:
939c20789501 Uploaded
rico
parents:
diff changeset
8 from dummy_thread import get_ident as _get_ident
939c20789501 Uploaded
rico
parents:
diff changeset
9
939c20789501 Uploaded
rico
parents:
diff changeset
10 try:
939c20789501 Uploaded
rico
parents:
diff changeset
11 from _abcoll import KeysView, ValuesView, ItemsView
939c20789501 Uploaded
rico
parents:
diff changeset
12 except ImportError:
939c20789501 Uploaded
rico
parents:
diff changeset
13 pass
939c20789501 Uploaded
rico
parents:
diff changeset
14
939c20789501 Uploaded
rico
parents:
diff changeset
15
939c20789501 Uploaded
rico
parents:
diff changeset
16 class OrderedDict(dict):
939c20789501 Uploaded
rico
parents:
diff changeset
17 'Dictionary that remembers insertion order'
939c20789501 Uploaded
rico
parents:
diff changeset
18 # An inherited dict maps keys to values.
939c20789501 Uploaded
rico
parents:
diff changeset
19 # The inherited dict provides __getitem__, __len__, __contains__, and get.
939c20789501 Uploaded
rico
parents:
diff changeset
20 # The remaining methods are order-aware.
939c20789501 Uploaded
rico
parents:
diff changeset
21 # Big-O running times for all methods are the same as for regular dictionaries.
939c20789501 Uploaded
rico
parents:
diff changeset
22
939c20789501 Uploaded
rico
parents:
diff changeset
23 # The internal self.__map dictionary maps keys to links in a doubly linked list.
939c20789501 Uploaded
rico
parents:
diff changeset
24 # The circular doubly linked list starts and ends with a sentinel element.
939c20789501 Uploaded
rico
parents:
diff changeset
25 # The sentinel element never gets deleted (this simplifies the algorithm).
939c20789501 Uploaded
rico
parents:
diff changeset
26 # Each link is stored as a list of length three: [PREV, NEXT, KEY].
939c20789501 Uploaded
rico
parents:
diff changeset
27
939c20789501 Uploaded
rico
parents:
diff changeset
28 def __init__(self, *args, **kwds):
939c20789501 Uploaded
rico
parents:
diff changeset
29 '''Initialize an ordered dictionary. Signature is the same as for
939c20789501 Uploaded
rico
parents:
diff changeset
30 regular dictionaries, but keyword arguments are not recommended
939c20789501 Uploaded
rico
parents:
diff changeset
31 because their insertion order is arbitrary.
939c20789501 Uploaded
rico
parents:
diff changeset
32
939c20789501 Uploaded
rico
parents:
diff changeset
33 '''
939c20789501 Uploaded
rico
parents:
diff changeset
34 if len(args) > 1:
939c20789501 Uploaded
rico
parents:
diff changeset
35 raise TypeError('expected at most 1 arguments, got %d' % len(args))
939c20789501 Uploaded
rico
parents:
diff changeset
36 try:
939c20789501 Uploaded
rico
parents:
diff changeset
37 self.__root
939c20789501 Uploaded
rico
parents:
diff changeset
38 except AttributeError:
939c20789501 Uploaded
rico
parents:
diff changeset
39 self.__root = root = [] # sentinel node
939c20789501 Uploaded
rico
parents:
diff changeset
40 root[:] = [root, root, None]
939c20789501 Uploaded
rico
parents:
diff changeset
41 self.__map = {}
939c20789501 Uploaded
rico
parents:
diff changeset
42 self.__update(*args, **kwds)
939c20789501 Uploaded
rico
parents:
diff changeset
43
939c20789501 Uploaded
rico
parents:
diff changeset
44 def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
939c20789501 Uploaded
rico
parents:
diff changeset
45 'od.__setitem__(i, y) <==> od[i]=y'
939c20789501 Uploaded
rico
parents:
diff changeset
46 # Setting a new item creates a new link which goes at the end of the linked
939c20789501 Uploaded
rico
parents:
diff changeset
47 # list, and the inherited dictionary is updated with the new key/value pair.
939c20789501 Uploaded
rico
parents:
diff changeset
48 if key not in self:
939c20789501 Uploaded
rico
parents:
diff changeset
49 root = self.__root
939c20789501 Uploaded
rico
parents:
diff changeset
50 last = root[0]
939c20789501 Uploaded
rico
parents:
diff changeset
51 last[1] = root[0] = self.__map[key] = [last, root, key]
939c20789501 Uploaded
rico
parents:
diff changeset
52 dict_setitem(self, key, value)
939c20789501 Uploaded
rico
parents:
diff changeset
53
939c20789501 Uploaded
rico
parents:
diff changeset
54 def __delitem__(self, key, dict_delitem=dict.__delitem__):
939c20789501 Uploaded
rico
parents:
diff changeset
55 'od.__delitem__(y) <==> del od[y]'
939c20789501 Uploaded
rico
parents:
diff changeset
56 # Deleting an existing item uses self.__map to find the link which is
939c20789501 Uploaded
rico
parents:
diff changeset
57 # then removed by updating the links in the predecessor and successor nodes.
939c20789501 Uploaded
rico
parents:
diff changeset
58 dict_delitem(self, key)
939c20789501 Uploaded
rico
parents:
diff changeset
59 link_prev, link_next, key = self.__map.pop(key)
939c20789501 Uploaded
rico
parents:
diff changeset
60 link_prev[1] = link_next
939c20789501 Uploaded
rico
parents:
diff changeset
61 link_next[0] = link_prev
939c20789501 Uploaded
rico
parents:
diff changeset
62
939c20789501 Uploaded
rico
parents:
diff changeset
63 def __iter__(self):
939c20789501 Uploaded
rico
parents:
diff changeset
64 'od.__iter__() <==> iter(od)'
939c20789501 Uploaded
rico
parents:
diff changeset
65 root = self.__root
939c20789501 Uploaded
rico
parents:
diff changeset
66 curr = root[1]
939c20789501 Uploaded
rico
parents:
diff changeset
67 while curr is not root:
939c20789501 Uploaded
rico
parents:
diff changeset
68 yield curr[2]
939c20789501 Uploaded
rico
parents:
diff changeset
69 curr = curr[1]
939c20789501 Uploaded
rico
parents:
diff changeset
70
939c20789501 Uploaded
rico
parents:
diff changeset
71 def __reversed__(self):
939c20789501 Uploaded
rico
parents:
diff changeset
72 'od.__reversed__() <==> reversed(od)'
939c20789501 Uploaded
rico
parents:
diff changeset
73 root = self.__root
939c20789501 Uploaded
rico
parents:
diff changeset
74 curr = root[0]
939c20789501 Uploaded
rico
parents:
diff changeset
75 while curr is not root:
939c20789501 Uploaded
rico
parents:
diff changeset
76 yield curr[2]
939c20789501 Uploaded
rico
parents:
diff changeset
77 curr = curr[0]
939c20789501 Uploaded
rico
parents:
diff changeset
78
939c20789501 Uploaded
rico
parents:
diff changeset
79 def clear(self):
939c20789501 Uploaded
rico
parents:
diff changeset
80 'od.clear() -> None. Remove all items from od.'
939c20789501 Uploaded
rico
parents:
diff changeset
81 try:
939c20789501 Uploaded
rico
parents:
diff changeset
82 for node in self.__map.itervalues():
939c20789501 Uploaded
rico
parents:
diff changeset
83 del node[:]
939c20789501 Uploaded
rico
parents:
diff changeset
84 root = self.__root
939c20789501 Uploaded
rico
parents:
diff changeset
85 root[:] = [root, root, None]
939c20789501 Uploaded
rico
parents:
diff changeset
86 self.__map.clear()
939c20789501 Uploaded
rico
parents:
diff changeset
87 except AttributeError:
939c20789501 Uploaded
rico
parents:
diff changeset
88 pass
939c20789501 Uploaded
rico
parents:
diff changeset
89 dict.clear(self)
939c20789501 Uploaded
rico
parents:
diff changeset
90
939c20789501 Uploaded
rico
parents:
diff changeset
91 def popitem(self, last=True):
939c20789501 Uploaded
rico
parents:
diff changeset
92 '''od.popitem() -> (k, v), return and remove a (key, value) pair.
939c20789501 Uploaded
rico
parents:
diff changeset
93 Pairs are returned in LIFO order if last is true or FIFO order if false.
939c20789501 Uploaded
rico
parents:
diff changeset
94
939c20789501 Uploaded
rico
parents:
diff changeset
95 '''
939c20789501 Uploaded
rico
parents:
diff changeset
96 if not self:
939c20789501 Uploaded
rico
parents:
diff changeset
97 raise KeyError('dictionary is empty')
939c20789501 Uploaded
rico
parents:
diff changeset
98 root = self.__root
939c20789501 Uploaded
rico
parents:
diff changeset
99 if last:
939c20789501 Uploaded
rico
parents:
diff changeset
100 link = root[0]
939c20789501 Uploaded
rico
parents:
diff changeset
101 link_prev = link[0]
939c20789501 Uploaded
rico
parents:
diff changeset
102 link_prev[1] = root
939c20789501 Uploaded
rico
parents:
diff changeset
103 root[0] = link_prev
939c20789501 Uploaded
rico
parents:
diff changeset
104 else:
939c20789501 Uploaded
rico
parents:
diff changeset
105 link = root[1]
939c20789501 Uploaded
rico
parents:
diff changeset
106 link_next = link[1]
939c20789501 Uploaded
rico
parents:
diff changeset
107 root[1] = link_next
939c20789501 Uploaded
rico
parents:
diff changeset
108 link_next[0] = root
939c20789501 Uploaded
rico
parents:
diff changeset
109 key = link[2]
939c20789501 Uploaded
rico
parents:
diff changeset
110 del self.__map[key]
939c20789501 Uploaded
rico
parents:
diff changeset
111 value = dict.pop(self, key)
939c20789501 Uploaded
rico
parents:
diff changeset
112 return key, value
939c20789501 Uploaded
rico
parents:
diff changeset
113
939c20789501 Uploaded
rico
parents:
diff changeset
114 # -- the following methods do not depend on the internal structure --
939c20789501 Uploaded
rico
parents:
diff changeset
115
939c20789501 Uploaded
rico
parents:
diff changeset
116 def keys(self):
939c20789501 Uploaded
rico
parents:
diff changeset
117 'od.keys() -> list of keys in od'
939c20789501 Uploaded
rico
parents:
diff changeset
118 return list(self)
939c20789501 Uploaded
rico
parents:
diff changeset
119
939c20789501 Uploaded
rico
parents:
diff changeset
120 def values(self):
939c20789501 Uploaded
rico
parents:
diff changeset
121 'od.values() -> list of values in od'
939c20789501 Uploaded
rico
parents:
diff changeset
122 return [self[key] for key in self]
939c20789501 Uploaded
rico
parents:
diff changeset
123
939c20789501 Uploaded
rico
parents:
diff changeset
124 def items(self):
939c20789501 Uploaded
rico
parents:
diff changeset
125 'od.items() -> list of (key, value) pairs in od'
939c20789501 Uploaded
rico
parents:
diff changeset
126 return [(key, self[key]) for key in self]
939c20789501 Uploaded
rico
parents:
diff changeset
127
939c20789501 Uploaded
rico
parents:
diff changeset
128 def iterkeys(self):
939c20789501 Uploaded
rico
parents:
diff changeset
129 'od.iterkeys() -> an iterator over the keys in od'
939c20789501 Uploaded
rico
parents:
diff changeset
130 return iter(self)
939c20789501 Uploaded
rico
parents:
diff changeset
131
939c20789501 Uploaded
rico
parents:
diff changeset
132 def itervalues(self):
939c20789501 Uploaded
rico
parents:
diff changeset
133 'od.itervalues -> an iterator over the values in od'
939c20789501 Uploaded
rico
parents:
diff changeset
134 for k in self:
939c20789501 Uploaded
rico
parents:
diff changeset
135 yield self[k]
939c20789501 Uploaded
rico
parents:
diff changeset
136
939c20789501 Uploaded
rico
parents:
diff changeset
137 def iteritems(self):
939c20789501 Uploaded
rico
parents:
diff changeset
138 'od.iteritems -> an iterator over the (key, value) items in od'
939c20789501 Uploaded
rico
parents:
diff changeset
139 for k in self:
939c20789501 Uploaded
rico
parents:
diff changeset
140 yield (k, self[k])
939c20789501 Uploaded
rico
parents:
diff changeset
141
939c20789501 Uploaded
rico
parents:
diff changeset
142 def update(*args, **kwds):
939c20789501 Uploaded
rico
parents:
diff changeset
143 '''od.update(E, **F) -> None. Update od from dict/iterable E and F.
939c20789501 Uploaded
rico
parents:
diff changeset
144
939c20789501 Uploaded
rico
parents:
diff changeset
145 If E is a dict instance, does: for k in E: od[k] = E[k]
939c20789501 Uploaded
rico
parents:
diff changeset
146 If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
939c20789501 Uploaded
rico
parents:
diff changeset
147 Or if E is an iterable of items, does: for k, v in E: od[k] = v
939c20789501 Uploaded
rico
parents:
diff changeset
148 In either case, this is followed by: for k, v in F.items(): od[k] = v
939c20789501 Uploaded
rico
parents:
diff changeset
149
939c20789501 Uploaded
rico
parents:
diff changeset
150 '''
939c20789501 Uploaded
rico
parents:
diff changeset
151 if len(args) > 2:
939c20789501 Uploaded
rico
parents:
diff changeset
152 raise TypeError('update() takes at most 2 positional '
939c20789501 Uploaded
rico
parents:
diff changeset
153 'arguments (%d given)' % (len(args),))
939c20789501 Uploaded
rico
parents:
diff changeset
154 elif not args:
939c20789501 Uploaded
rico
parents:
diff changeset
155 raise TypeError('update() takes at least 1 argument (0 given)')
939c20789501 Uploaded
rico
parents:
diff changeset
156 self = args[0]
939c20789501 Uploaded
rico
parents:
diff changeset
157 # Make progressively weaker assumptions about "other"
939c20789501 Uploaded
rico
parents:
diff changeset
158 other = ()
939c20789501 Uploaded
rico
parents:
diff changeset
159 if len(args) == 2:
939c20789501 Uploaded
rico
parents:
diff changeset
160 other = args[1]
939c20789501 Uploaded
rico
parents:
diff changeset
161 if isinstance(other, dict):
939c20789501 Uploaded
rico
parents:
diff changeset
162 for key in other:
939c20789501 Uploaded
rico
parents:
diff changeset
163 self[key] = other[key]
939c20789501 Uploaded
rico
parents:
diff changeset
164 elif hasattr(other, 'keys'):
939c20789501 Uploaded
rico
parents:
diff changeset
165 for key in other.keys():
939c20789501 Uploaded
rico
parents:
diff changeset
166 self[key] = other[key]
939c20789501 Uploaded
rico
parents:
diff changeset
167 else:
939c20789501 Uploaded
rico
parents:
diff changeset
168 for key, value in other:
939c20789501 Uploaded
rico
parents:
diff changeset
169 self[key] = value
939c20789501 Uploaded
rico
parents:
diff changeset
170 for key, value in kwds.items():
939c20789501 Uploaded
rico
parents:
diff changeset
171 self[key] = value
939c20789501 Uploaded
rico
parents:
diff changeset
172
939c20789501 Uploaded
rico
parents:
diff changeset
173 __update = update # let subclasses override update without breaking __init__
939c20789501 Uploaded
rico
parents:
diff changeset
174
939c20789501 Uploaded
rico
parents:
diff changeset
175 __marker = object()
939c20789501 Uploaded
rico
parents:
diff changeset
176
939c20789501 Uploaded
rico
parents:
diff changeset
177 def pop(self, key, default=__marker):
939c20789501 Uploaded
rico
parents:
diff changeset
178 '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
939c20789501 Uploaded
rico
parents:
diff changeset
179 If key is not found, d is returned if given, otherwise KeyError is raised.
939c20789501 Uploaded
rico
parents:
diff changeset
180
939c20789501 Uploaded
rico
parents:
diff changeset
181 '''
939c20789501 Uploaded
rico
parents:
diff changeset
182 if key in self:
939c20789501 Uploaded
rico
parents:
diff changeset
183 result = self[key]
939c20789501 Uploaded
rico
parents:
diff changeset
184 del self[key]
939c20789501 Uploaded
rico
parents:
diff changeset
185 return result
939c20789501 Uploaded
rico
parents:
diff changeset
186 if default is self.__marker:
939c20789501 Uploaded
rico
parents:
diff changeset
187 raise KeyError(key)
939c20789501 Uploaded
rico
parents:
diff changeset
188 return default
939c20789501 Uploaded
rico
parents:
diff changeset
189
939c20789501 Uploaded
rico
parents:
diff changeset
190 def setdefault(self, key, default=None):
939c20789501 Uploaded
rico
parents:
diff changeset
191 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
939c20789501 Uploaded
rico
parents:
diff changeset
192 if key in self:
939c20789501 Uploaded
rico
parents:
diff changeset
193 return self[key]
939c20789501 Uploaded
rico
parents:
diff changeset
194 self[key] = default
939c20789501 Uploaded
rico
parents:
diff changeset
195 return default
939c20789501 Uploaded
rico
parents:
diff changeset
196
939c20789501 Uploaded
rico
parents:
diff changeset
197 def __repr__(self, _repr_running={}):
939c20789501 Uploaded
rico
parents:
diff changeset
198 'od.__repr__() <==> repr(od)'
939c20789501 Uploaded
rico
parents:
diff changeset
199 call_key = id(self), _get_ident()
939c20789501 Uploaded
rico
parents:
diff changeset
200 if call_key in _repr_running:
939c20789501 Uploaded
rico
parents:
diff changeset
201 return '...'
939c20789501 Uploaded
rico
parents:
diff changeset
202 _repr_running[call_key] = 1
939c20789501 Uploaded
rico
parents:
diff changeset
203 try:
939c20789501 Uploaded
rico
parents:
diff changeset
204 if not self:
939c20789501 Uploaded
rico
parents:
diff changeset
205 return '%s()' % (self.__class__.__name__,)
939c20789501 Uploaded
rico
parents:
diff changeset
206 return '%s(%r)' % (self.__class__.__name__, self.items())
939c20789501 Uploaded
rico
parents:
diff changeset
207 finally:
939c20789501 Uploaded
rico
parents:
diff changeset
208 del _repr_running[call_key]
939c20789501 Uploaded
rico
parents:
diff changeset
209
939c20789501 Uploaded
rico
parents:
diff changeset
210 def __reduce__(self):
939c20789501 Uploaded
rico
parents:
diff changeset
211 'Return state information for pickling'
939c20789501 Uploaded
rico
parents:
diff changeset
212 items = [[k, self[k]] for k in self]
939c20789501 Uploaded
rico
parents:
diff changeset
213 inst_dict = vars(self).copy()
939c20789501 Uploaded
rico
parents:
diff changeset
214 for k in vars(OrderedDict()):
939c20789501 Uploaded
rico
parents:
diff changeset
215 inst_dict.pop(k, None)
939c20789501 Uploaded
rico
parents:
diff changeset
216 if inst_dict:
939c20789501 Uploaded
rico
parents:
diff changeset
217 return (self.__class__, (items,), inst_dict)
939c20789501 Uploaded
rico
parents:
diff changeset
218 return self.__class__, (items,)
939c20789501 Uploaded
rico
parents:
diff changeset
219
939c20789501 Uploaded
rico
parents:
diff changeset
220 def copy(self):
939c20789501 Uploaded
rico
parents:
diff changeset
221 'od.copy() -> a shallow copy of od'
939c20789501 Uploaded
rico
parents:
diff changeset
222 return self.__class__(self)
939c20789501 Uploaded
rico
parents:
diff changeset
223
939c20789501 Uploaded
rico
parents:
diff changeset
224 @classmethod
939c20789501 Uploaded
rico
parents:
diff changeset
225 def fromkeys(cls, iterable, value=None):
939c20789501 Uploaded
rico
parents:
diff changeset
226 '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
939c20789501 Uploaded
rico
parents:
diff changeset
227 and values equal to v (which defaults to None).
939c20789501 Uploaded
rico
parents:
diff changeset
228
939c20789501 Uploaded
rico
parents:
diff changeset
229 '''
939c20789501 Uploaded
rico
parents:
diff changeset
230 d = cls()
939c20789501 Uploaded
rico
parents:
diff changeset
231 for key in iterable:
939c20789501 Uploaded
rico
parents:
diff changeset
232 d[key] = value
939c20789501 Uploaded
rico
parents:
diff changeset
233 return d
939c20789501 Uploaded
rico
parents:
diff changeset
234
939c20789501 Uploaded
rico
parents:
diff changeset
235 def __eq__(self, other):
939c20789501 Uploaded
rico
parents:
diff changeset
236 '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
939c20789501 Uploaded
rico
parents:
diff changeset
237 while comparison to a regular mapping is order-insensitive.
939c20789501 Uploaded
rico
parents:
diff changeset
238
939c20789501 Uploaded
rico
parents:
diff changeset
239 '''
939c20789501 Uploaded
rico
parents:
diff changeset
240 if isinstance(other, OrderedDict):
939c20789501 Uploaded
rico
parents:
diff changeset
241 return len(self)==len(other) and self.items() == other.items()
939c20789501 Uploaded
rico
parents:
diff changeset
242 return dict.__eq__(self, other)
939c20789501 Uploaded
rico
parents:
diff changeset
243
939c20789501 Uploaded
rico
parents:
diff changeset
244 def __ne__(self, other):
939c20789501 Uploaded
rico
parents:
diff changeset
245 return not self == other
939c20789501 Uploaded
rico
parents:
diff changeset
246
939c20789501 Uploaded
rico
parents:
diff changeset
247 # -- the following methods are only used in Python 2.7 --
939c20789501 Uploaded
rico
parents:
diff changeset
248
939c20789501 Uploaded
rico
parents:
diff changeset
249 def viewkeys(self):
939c20789501 Uploaded
rico
parents:
diff changeset
250 "od.viewkeys() -> a set-like object providing a view on od's keys"
939c20789501 Uploaded
rico
parents:
diff changeset
251 return KeysView(self)
939c20789501 Uploaded
rico
parents:
diff changeset
252
939c20789501 Uploaded
rico
parents:
diff changeset
253 def viewvalues(self):
939c20789501 Uploaded
rico
parents:
diff changeset
254 "od.viewvalues() -> an object providing a view on od's values"
939c20789501 Uploaded
rico
parents:
diff changeset
255 return ValuesView(self)
939c20789501 Uploaded
rico
parents:
diff changeset
256
939c20789501 Uploaded
rico
parents:
diff changeset
257 def viewitems(self):
939c20789501 Uploaded
rico
parents:
diff changeset
258 "od.viewitems() -> a set-like object providing a view on od's items"
939c20789501 Uploaded
rico
parents:
diff changeset
259 return ItemsView(self)