1 """Drop-in replacement for collections.OrderedDict by Raymond Hettinger
3 http://code.activestate.com/recipes/576693/
6 from UserDict
import DictMixin
8 class OrderedDict(dict, DictMixin
):
10 def __init__(self
, *args
, **kwds
):
12 raise TypeError('expected at most 1 arguments, got %d' % len(args
))
15 except AttributeError:
17 self
.update(*args
, **kwds
)
21 end
+= [None, end
, end
] # sentinel node for doubly linked list
22 self
.__map
= {} # key --> [key, prev, next]
25 def __setitem__(self
, key
, value
):
29 curr
[2] = end
[1] = self
.__map
[key
] = [key
, curr
, end
]
30 dict.__setitem
__(self
, key
, value
)
32 def __delitem__(self
, key
):
33 dict.__delitem
__(self
, key
)
34 key
, prev
, next
= self
.__map
.pop(key
)
41 while curr
is not end
:
45 def __reversed__(self
):
48 while curr
is not end
:
52 def popitem(self
, last
=True):
54 raise KeyError('dictionary is empty')
56 key
= reversed(self
).next()
58 key
= iter(self
).next()
63 items
= [[k
, self
[k
]] for k
in self
]
64 tmp
= self
.__map
, self
.__end
65 del self
.__map
, self
.__end
66 inst_dict
= vars(self
).copy()
67 self
.__map
, self
.__end
= tmp
69 return (self
.__class
__, (items
,), inst_dict
)
70 return self
.__class
__, (items
,)
75 setdefault
= DictMixin
.setdefault
76 update
= DictMixin
.update
78 values
= DictMixin
.values
79 items
= DictMixin
.items
80 iterkeys
= DictMixin
.iterkeys
81 itervalues
= DictMixin
.itervalues
82 iteritems
= DictMixin
.iteritems
86 return '%s()' % (self
.__class
__.__name
__,)
87 return '%s(%r)' % (self
.__class
__.__name
__, self
.items())
90 return self
.__class
__(self
)
93 def fromkeys(cls
, iterable
, value
=None):
99 def __eq__(self
, other
):
100 if isinstance(other
, OrderedDict
):
101 return len(self
)==len(other
) and \
102 all(p
==q
for p
, q
in zip(self
.items(), other
.items()))
103 return dict.__eq
__(self
, other
)
105 def __ne__(self
, other
):
106 return not self
== other