Recipe 5.1. Sorting a Dictionary
Credit: Alex Martelli
Problem
You
want to sort a dictionary. This probably means that you want to sort
the keys and then get the values in that same sorted order.
Solution
The simplest approach is exactly the one expressed by the problem
statement: sort the keys, then pick the corresponding values:
def sortedDictValues(adict):
keys = adict.keys( )
keys.sort( )
return [adict[key] for key in keys]
Discussion
The concept of sorting applies only to a collection that has an
orderin 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, though literally meaningless, question on the Python lists.
More often than not, the question is in fact about sorting some
sequence composed of keys and/or values from the dictionary.As for the implementation, while one could think of more
sophisticated approaches, it turns out (not unusually, for Python)
that the one shown in the solution, the simplest one, is also
essentially the fastest one. A further slight increase in speed,
about 20%, can be squeezed out in Python 2.3 by replacing the list
comprehension with a map call in the
return statement at the end of the function. For
example:
return map(adict.get, keys)Python 2.4, however, is already measurably faster than Python 2.3
with the version in the "Solution"
and gains nothing from this further step. Other variants, such as
using adict._ _getitem_ _ instead of
adict.get, offer no further increase in speed, or
they even slow performance down a little, in both Python 2.3 and 2.4.
See Also
Recipe 5.4 for sorting a
dictionary based on its values rather than on its keys.