summaryrefslogtreecommitdiffstats
path: root/Doc/library
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2011-04-16 00:43:19 (GMT)
committerRaymond Hettinger <python@rcn.com>2011-04-16 00:43:19 (GMT)
commit7bba683d27a82856f93f72370f273025579d3a13 (patch)
tree0477734574496a7fc6ea276a05b4bc85c3eb9d17 /Doc/library
parent1c746c28f3cfe798ed4d7b51f50adaa685a4fb0e (diff)
downloadcpython-7bba683d27a82856f93f72370f273025579d3a13.zip
cpython-7bba683d27a82856f93f72370f273025579d3a13.tar.gz
cpython-7bba683d27a82856f93f72370f273025579d3a13.tar.bz2
Add another example to the collections module docs.
Diffstat (limited to 'Doc/library')
-rw-r--r--Doc/library/collections.rst20
1 files changed, 20 insertions, 0 deletions
diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst
index 02415f7..68a79f1 100644
--- a/Doc/library/collections.rst
+++ b/Doc/library/collections.rst
@@ -783,6 +783,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::
@@ -812,11 +815,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
-------------------------