[Python-checkins] r76187 - python/branches/release31-maint/Doc/library/collections.rst

raymond.hettinger python-checkins at python.org
Tue Nov 10 19:21:06 CET 2009


Author: raymond.hettinger
Date: Tue Nov 10 19:21:06 2009
New Revision: 76187

Log:
Show example of how to make a sorted dictionary

Modified:
   python/branches/release31-maint/Doc/library/collections.rst

Modified: python/branches/release31-maint/Doc/library/collections.rst
==============================================================================
--- python/branches/release31-maint/Doc/library/collections.rst	(original)
+++ python/branches/release31-maint/Doc/library/collections.rst	Tue Nov 10 19:21:06 2009
@@ -862,6 +862,28 @@
    `Equivalent OrderedDict recipe <http://code.activestate.com/recipes/576693/>`_
    that runs on Python 2.4 or later.
 
+Since an ordered dictionary remembers its insertion order, it can be used
+in conjuction with sorting to make a sorted dictionary::
+
+    >>> # regular unsorted dictionary
+    >>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
+
+    >>> # dictionary sorted by key
+    >>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
+    OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
+
+    >>> # dictionary sorted by value
+    >>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
+    OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
+
+    >>> # dictionary sorted by length of the key string
+    >>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
+    OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
+
+The new sorted dictionaries maintain their sort order when entries
+are deleted.  But when new keys are added, the keys are appended
+to the end and the sort is not maintained.
+
 
 :class:`UserDict` objects
 -------------------------


More information about the Python-checkins mailing list