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