how to sort a dictionary by the values ?

A.M. Kuchling amk at
Sat Dec 30 17:14:30 CET 2000

On Sat, 30 Dec 2000 21:16:13 +0900, 
	June Kim <junaftnoon at> wrote:
> >>> dic={ ... }
> >>> z=dic.items()
> >>> z.sort(lambda x,y:cmp(x[1],y[1]))

Note that this won't compare the keys at all, then; the resulting list
would be sorted by the value, and tuples with the same value would be
ordered randomly.  lambda x,y: cmp( (x[1], x[0]), (y[1], y[0]) ) would
sort by value and then key.  But look at all the tuple construction
and destruction going on; it would be even slower.  It might be
preferable, depending on the size of the dictionary and what you're
doing with the list 'z', to reverse all the tuples first and then sort

>>> z = map(lambda x: (x[1], x[0]), z)
>>> z.sort()


More information about the Python-list mailing list