odict.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. class OrderedDict(dict):
  2. """
  3. A dictionary that keeps its keys in the order in which they're inserted.
  4. Copied from Django's SortedDict with some modifications.
  5. """
  6. def __new__(cls, *args, **kwargs):
  7. instance = super(OrderedDict, cls).__new__(cls, *args, **kwargs)
  8. instance.keyOrder = []
  9. return instance
  10. def __init__(self, data=None):
  11. if data is None:
  12. data = {}
  13. super(OrderedDict, self).__init__(data)
  14. if isinstance(data, dict):
  15. self.keyOrder = data.keys()
  16. else:
  17. self.keyOrder = []
  18. for key, value in data:
  19. if key not in self.keyOrder:
  20. self.keyOrder.append(key)
  21. def __deepcopy__(self, memo):
  22. from copy import deepcopy
  23. return self.__class__([(key, deepcopy(value, memo))
  24. for key, value in self.iteritems()])
  25. def __setitem__(self, key, value):
  26. super(OrderedDict, self).__setitem__(key, value)
  27. if key not in self.keyOrder:
  28. self.keyOrder.append(key)
  29. def __delitem__(self, key):
  30. super(OrderedDict, self).__delitem__(key)
  31. self.keyOrder.remove(key)
  32. def __iter__(self):
  33. for k in self.keyOrder:
  34. yield k
  35. def pop(self, k, *args):
  36. result = super(OrderedDict, self).pop(k, *args)
  37. try:
  38. self.keyOrder.remove(k)
  39. except ValueError:
  40. # Key wasn't in the dictionary in the first place. No problem.
  41. pass
  42. return result
  43. def popitem(self):
  44. result = super(OrderedDict, self).popitem()
  45. self.keyOrder.remove(result[0])
  46. return result
  47. def items(self):
  48. return zip(self.keyOrder, self.values())
  49. def iteritems(self):
  50. for key in self.keyOrder:
  51. yield key, super(OrderedDict, self).__getitem__(key)
  52. def keys(self):
  53. return self.keyOrder[:]
  54. def iterkeys(self):
  55. return iter(self.keyOrder)
  56. def values(self):
  57. return [super(OrderedDict, self).__getitem__(k) for k in self.keyOrder]
  58. def itervalues(self):
  59. for key in self.keyOrder:
  60. yield super(OrderedDict, self).__getitem__(key)
  61. def update(self, dict_):
  62. for k, v in dict_.items():
  63. self.__setitem__(k, v)
  64. def setdefault(self, key, default):
  65. if key not in self.keyOrder:
  66. self.keyOrder.append(key)
  67. return super(OrderedDict, self).setdefault(key, default)
  68. def value_for_index(self, index):
  69. """Return the value of the item at the given zero-based index."""
  70. return self[self.keyOrder[index]]
  71. def insert(self, index, key, value):
  72. """Insert the key, value pair before the item with the given index."""
  73. if key in self.keyOrder:
  74. n = self.keyOrder.index(key)
  75. del self.keyOrder[n]
  76. if n < index:
  77. index -= 1
  78. self.keyOrder.insert(index, key)
  79. super(OrderedDict, self).__setitem__(key, value)
  80. def copy(self):
  81. """Return a copy of this object."""
  82. # This way of initializing the copy means it works for subclasses, too.
  83. obj = self.__class__(self)
  84. obj.keyOrder = self.keyOrder[:]
  85. return obj
  86. def __repr__(self):
  87. """
  88. Replace the normal dict.__repr__ with a version that returns the keys
  89. in their sorted order.
  90. """
  91. return '{%s}' % ', '.join(['%r: %r' % (k, v) for k, v in self.items()])
  92. def clear(self):
  93. super(OrderedDict, self).clear()
  94. self.keyOrder = []
  95. def index(self, key):
  96. """ Return the index of a given key. """
  97. return self.keyOrder.index(key)
  98. def index_for_location(self, location):
  99. """ Return index or None for a given location. """
  100. if location == '_begin':
  101. i = 0
  102. elif location == '_end':
  103. i = None
  104. elif location.startswith('<') or location.startswith('>'):
  105. i = self.index(location[1:])
  106. if location.startswith('>'):
  107. if i >= len(self):
  108. # last item
  109. i = None
  110. else:
  111. i += 1
  112. else:
  113. raise ValueError('Not a valid location: "%s". Location key '
  114. 'must start with a ">" or "<".' % location)
  115. return i
  116. def add(self, key, value, location):
  117. """ Insert by key location. """
  118. i = self.index_for_location(location)
  119. if i is not None:
  120. self.insert(i, key, value)
  121. else:
  122. self.__setitem__(key, value)
  123. def link(self, key, location):
  124. """ Change location of an existing item. """
  125. n = self.keyOrder.index(key)
  126. del self.keyOrder[n]
  127. i = self.index_for_location(location)
  128. try:
  129. if i is not None:
  130. self.keyOrder.insert(i, key)
  131. else:
  132. self.keyOrder.append(key)
  133. except Error:
  134. # restore to prevent data loss and reraise
  135. self.keyOrder.insert(n, key)
  136. raise Error