odict.py 8.7 KB

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