From df70a13b8f81f7a4563d94f07de1f11c9129484c Mon Sep 17 00:00:00 2001 From: "raymond.hettinger" Date: Tue, 10 Nov 2009 19:35:55 +0000 Subject: [PATCH] Show example of how to make a sorted dictionary git-svn-id: http://svn.python.org/projects/python/trunk@76194 6015fed2-1504-0410-9fe1-9d1591cc4771 --- Doc/library/collections.rst | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst index c0d539f658..dc81c0ad18 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -884,3 +884,25 @@ semantics pass-in keyword arguments using a regular unordered dictionary. `Equivalent OrderedDict recipe `_ 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. -- 2.11.4.GIT