An Ordered Dict records the order in which items are added. This implementation uses much less code than the others by extending not well-known class DictMixin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | from UserDict import DictMixin
class odict(DictMixin):
def __init__(self):
self._keys = []
self._data = {}
def __setitem__(self, key, value):
if key not in self._data:
self._keys.append(key)
self._data[key] = value
def __getitem__(self, key):
return self._data[key]
def __delitem__(self, key):
del self._data[key]
self._keys.remove(key)
def keys(self):
return list(self._keys)
def copy(self):
copyDict = odict()
copyDict._data = self._data.copy()
copyDict._keys = self._keys[:]
return copyDict
|
Tags: extending
Some Suggestions. Adding the following to odict should allow its constructor to act like the dict() factory function, will preserve element order when converting from ordered sequences, and should repr() in order.
And some tests:
And I suppose you could add this so you aren't copying self._keys when calling __iter__:
Also, you probably should have named this "OrderedDict", to go along with the Python naming conventions.
__repr__ Fix. Whoops, messed up __repr__ there. It should probably be something like this:
Slicing. Also, if you wanted to add slicing support, this should work:
odict not a dictionary. odict is a not really a dictionary. it can not be used as replacement of a dictionary.
for example the following code fails.
odict not a dictionary. This is a bug in the standard library, as UserDict is not a dictionary either:
In fact, I would classify this as a bug related to type checking and thus is a bug in the interpreter itself.
Re: odict not a dictionary.
FWIW, the problems previously mentioned with
DictMixin
andUserDict
not being considered dictionaries has apparently been fixed -- at least it appears to be in Python 2.6.2, the version installed on the machine I'm using.