## Stupid Python tricks, #3296: sorting a dictionary by its values

Suppose you have a dictionary **mydict**, with key:value pairs

mydict = {'a':5, 'b':2, 'c':1, 'd':6}

You want to sort the keys by the values, maintaining the keys first in a list of tuples, so that the final list will be:

[('c',1), ('b',2), ('a',5), ('d',6)]

aaaand, the stupid Python trick involves a nested list comprehension:

sorted_list = [(k,v) for v,k in sorted( [(v,k) for k,v in mydict.items()] ) ]

To get a reverse sorted list:

[('d',6), ('a',5),('b',2),('c',1)]

[(k,v) for v,k in sorted( [(v,k) for k,v in mydict.items()],reverse=True ) ]

This may be a better way to do it:

sorted(mydict.items(), key = lambda (k,v): v)

You are right. It is better. But it is not stupid.

import operator

mydict = {‘a':5, ‘b':2, ‘c':1, ‘d':6}

print sorted(mydict.iteritems(), key=operator.itemgetter(1))