Sorting a Dictionary
Credit: Alex Martelli, Raymond Hettinger
Problem
You want to sort a dictionary. Because sorting is a concept that only makes sense for sequences, this presumably means that you want a sequence of the values of the dictionary in the order obtained by sorting the keys.
Solution
The simplest approach is to sort the items (i.e., key/value pairs), then pick just the values:
def sortedDictValues1(adict):
items = adict.items( )
items.sort( )
return [value for key, value in items]However, an alternative implementation that sorts just the keys, then uses them to index into the dictionary to build the result, happens to run more than twice as fast (for a dictionary of a few thousand entries) on my system:
def sortedDictValues2(adict):
keys = adict.keys( )
keys.sort( )
return [adict[key] for key in keys]A further small speed-up (15% on my system) is to perform the last
step by mapping a bound method. map is often
marginally faster than a list comprehension when no
lambda is involved:
def sortedDictValues3(adict):
keys = adict.keys( )
keys.sort( )
return map(adict.get, keys)A really tiny extra speed-up (about 3% on my system) is available in
Python 2.2 by using adict._ _getitem_ _ rather
than adict.get in this latest, bound-method
version.
Discussion
The concept of sorting applies only to a collection that has order—in other words, a sequence. A mapping, such as a dictionary, has no order, so it cannot be sorted. And yet, “How do I sort a dictionary?” is a frequent question ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access