Skip to content

Commit 0e31201

Browse files
committed
Show example of how to make a sorted dictionary
1 parent 28cee96 commit 0e31201

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

Doc/library/collections.rst

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -862,6 +862,28 @@ semantics pass-in keyword arguments using a regular unordered dictionary.
862862
`Equivalent OrderedDict recipe <http://code.activestate.com/recipes/576693/>`_
863863
that runs on Python 2.4 or later.
864864

865+
Since an ordered dictionary remembers its insertion order, it can be used
866+
in conjuction with sorting to make a sorted dictionary::
867+
868+
>>> # regular unsorted dictionary
869+
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
870+
871+
>>> # dictionary sorted by key
872+
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
873+
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
874+
875+
>>> # dictionary sorted by value
876+
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
877+
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
878+
879+
>>> # dictionary sorted by length of the key string
880+
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
881+
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
882+
883+
The new sorted dictionaries maintain their sort order when entries
884+
are deleted. But when new keys are added, the keys are appended
885+
to the end and the sort is not maintained.
886+
865887

866888
:class:`UserDict` objects
867889
-------------------------

0 commit comments

Comments
 (0)