diff options
author | Raymond Hettinger <python@rcn.com> | 2011-04-16 00:44:30 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2011-04-16 00:44:30 (GMT) |
commit | 4c2ffab80b5dac8790c9c7219181db13a4ace07f (patch) | |
tree | 9d14b2c7919a4093884780443c6fb1676abf3cff /Doc/library/collections.rst | |
parent | cd5a2bd48ef2c8fa07a2d47833f5b51c8468aab6 (diff) | |
parent | f05c1394fe3c27e0fe33db984cf2f8bd9a4a1d47 (diff) | |
download | cpython-4c2ffab80b5dac8790c9c7219181db13a4ace07f.zip cpython-4c2ffab80b5dac8790c9c7219181db13a4ace07f.tar.gz cpython-4c2ffab80b5dac8790c9c7219181db13a4ace07f.tar.bz2 |
merge
Diffstat (limited to 'Doc/library/collections.rst')
-rw-r--r-- | Doc/library/collections.rst | 20 |
1 files changed, 20 insertions, 0 deletions
diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst index 21b0924..15ed173 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -927,6 +927,9 @@ semantics pass-in keyword arguments using a regular unordered dictionary. `Equivalent OrderedDict recipe <http://code.activestate.com/recipes/576693/>`_ that runs on Python 2.4 or later. +:class:`OrderedDict` Examples and Recipes +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Since an ordered dictionary remembers its insertion order, it can be used in conjuction with sorting to make a sorted dictionary:: @@ -956,11 +959,28 @@ original insertion position is changed and moved to the end:: class LastUpdatedOrderedDict(OrderedDict): 'Store items in the order the keys were last added' + def __setitem__(self, key, value): if key in self: del self[key] OrderedDict.__setitem__(self, key, value) +An ordered dictionary can combined with the :class:`Counter` class +so that the counter remembers the order elements are first encountered:: + + class OrderedCounter(Counter, OrderedDict): + 'Counter that remembers the order elements are first encountered' + + def __init__(self, iterable=None, **kwds): + OrderedDict.__init__(self) + Counter.__init__(self, iterable, **kwds) + + def __repr__(self): + return '%s(%r)' % (self.__class__.__name__, OrderedDict(self)) + + def __reduce__(self): + return self.__class__, (OrderedDict(self),) + :class:`UserDict` objects ------------------------- |