As an example, suppose we wish to create a dictionary that will ``remember'' the order
in which entries are added. Of course, this could be done by explicitly keeping a
list of the keys, but would be awkward to implement because each time an entry was added
to the dictionary, a separate statement would be needed to update the list. By overloading
the __setitem__
method, we can store each key as it is encountered; by providing
a new method (say, okeys), we can retrieve the ordered list. To simplify matters,
the __init__
method will not accept any arguments, so that the dictionary must be built
incrementally. (When a dictionary is initialized in the usual way, the keys are added in
a random order.) Here's an example of how such a dictionary could be implemented:
from UserDict import UserDict class ODict(UserDict): def __init__(self): self._okeys = [] self.data = {} def __setitem__(self,key,value): self.data[key] = value if key not in self._okeys: self._okeys.append(key) def okeys(self): return self._okeysAfter creating an object of type ODict, we can manipulate it just as any other dictionary, since, when you invoke an existing method, the UserDict class knows to operate on the data attribute of the object. However, the new okeys method is available to provide the keys in the order in which they were created:
>>> from odict import ODict >>> mydict = ODict() >>> words = ['cat','dog','duck','chicken','goat'] >>> for w in words: ... mydict[w] = len(w) ... >>> mydict.keys() ['goat', 'chicken', 'duck', 'dog', 'cat'] >>> mydict.okeys() ['cat', 'dog', 'duck', 'chicken', 'goat']