Thursday, November 26, 2009

Sorting dictionary values in Python

Python dictionary value sorting:
http://wiki.python.org/moin/HowTo/Sorting#Sortingbykeys

If the invocation of key returns a tuple, second and subsequent items in the tuple will be treated as sub-keys in the same way that Python generally sorts tuples:

>>> L = [('d', 2), ('a', 4), ('b', 3), ('c', 2)]
>>> sorted(L, key=lambda x:(x[1], x[0]))
[('c', 2), ('d', 2), ('b', 3), ('a', 4)]

No comments: