summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2009-11-10 18:35:46 (GMT)
committerRaymond Hettinger <python@rcn.com>2009-11-10 18:35:46 (GMT)
commit0e31201848f45db86bea6bf5bd196e2db88fbfbe (patch)
tree6dc745f677984ab2f19d56e4332276dd5b7c9ff5
parent28cee96ee1106aa5597f7b51be1a8ba0d2bdfcb2 (diff)
downloadcpython-0e31201848f45db86bea6bf5bd196e2db88fbfbe.zip
cpython-0e31201848f45db86bea6bf5bd196e2db88fbfbe.tar.gz
cpython-0e31201848f45db86bea6bf5bd196e2db88fbfbe.tar.bz2
Show example of how to make a sorted dictionary
-rw-r--r--Doc/library/collections.rst22
1 files changed, 22 insertions, 0 deletions
diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst
index cd38956..7770b89 100644
--- a/Doc/library/collections.rst
+++ b/Doc/library/collections.rst
@@ -862,6 +862,28 @@ 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.
+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
-------------------------