20090119

Sorting a dictionary by value

In Python you sometimes need to sort a dictionary based on its values, not the keys, as the built-in sorted function does:


>>> a = { 'a' : 1, 'b' : 3, 'd' : 2, 'c' : 4 }

>>> sorted (a)

['a', 'b', 'c', 'd']


Not exactly the output we wished for. This is because dictionary iterators iterate over the keys and not the values.


There are several possible solutions to this problem, the simplest is to add specific key parameter to sorted:


>>> sorted (a, key=(lambda x: a[x]))

['a', 'd', 'b', 'c']


This way you can iterate over the dictionary in the order of preference:


>>> for i in sorted (a, key=(lambda x: a[x])):

... print a[i]

...

1

2

3

4


Note that if you try to construct a dictionary from the sorted list it will not yield a sorted dictionary:


>>> dict ([(x, a[x]) for x in sorted (a, key=(lambda z: a[z]))])

{'a': 1, 'c': 4, 'b': 3, 'd': 2}


Dictionaries uses hashes, so the order is not guaranteed. This is why you have to construct a temporary list with the sorted keys to iterate over the dictionary in the desired order (in this case sorted by the value). In real world scenarios you sometimes have a dictionary of dictionaries, and this way you can choose the parameter you iterate over.


No comments:

Post a Comment