diff options
author | Raymond Hettinger <python@rcn.com> | 2011-04-15 17:55:36 -0700 |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2011-04-15 17:55:36 -0700 |
commit | df453fbb5fe24ae2e0141f4d7e568696457ffe4d (patch) | |
tree | b887fb1a11c1ce35cd015465626e034e4b9f9fd8 | |
parent | 37c0fe56b9053f5f388ba6d6217506a6e73bb819 (diff) | |
download | cpython-git-df453fbb5fe24ae2e0141f4d7e568696457ffe4d.tar.gz |
Add another example to the collections module docs.
-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 48cac2f6c9..88c4f0f9ee 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -818,6 +818,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:: @@ -846,12 +849,29 @@ If a new entry overwrites an existing entry, the 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),) + .. _abstract-base-classes: |