1 """Drop-in replacement for collections.OrderedDict by Raymond Hettinger
3 http://code.activestate.com/recipes/576693/
6 from UserDict import DictMixin
8 # Modified from original to support Python 2.4, see
9 # http://code.google.com/p/simplejson/issues/detail?id=53
19 class OrderedDict(dict, DictMixin):
21 def __init__(self, *args, **kwds):
23 raise TypeError('expected at most 1 arguments, got %d' % len(args))
26 except AttributeError:
28 self.update(*args, **kwds)
32 end += [None, end, end] # sentinel node for doubly linked list
33 self.__map = {} # key --> [key, prev, next]
36 def __setitem__(self, key, value):
40 curr[2] = end[1] = self.__map[key] = [key, curr, end]
41 dict.__setitem__(self, key, value)
43 def __delitem__(self, key):
44 dict.__delitem__(self, key)
45 key, prev, next = self.__map.pop(key)
52 while curr is not end:
56 def __reversed__(self):
59 while curr is not end:
63 def popitem(self, last=True):
65 raise KeyError('dictionary is empty')
66 # Modified from original to support Python 2.4, see
67 # http://code.google.com/p/simplejson/issues/detail?id=53
69 key = reversed(self).next()
71 key = iter(self).next()
76 items = [[k, self[k]] for k in self]
77 tmp = self.__map, self.__end
78 del self.__map, self.__end
79 inst_dict = vars(self).copy()
80 self.__map, self.__end = tmp
82 return (self.__class__, (items,), inst_dict)
83 return self.__class__, (items,)
88 setdefault = DictMixin.setdefault
89 update = DictMixin.update
91 values = DictMixin.values
92 items = DictMixin.items
93 iterkeys = DictMixin.iterkeys
94 itervalues = DictMixin.itervalues
95 iteritems = DictMixin.iteritems
99 return '%s()' % (self.__class__.__name__,)
100 return '%s(%r)' % (self.__class__.__name__, self.items())
103 return self.__class__(self)
106 def fromkeys(cls, iterable, value=None):
112 def __eq__(self, other):
113 if isinstance(other, OrderedDict):
114 return len(self)==len(other) and \
115 all(p==q for p, q in zip(self.items(), other.items()))
116 return dict.__eq__(self, other)
118 def __ne__(self, other):
119 return not self == other