Skip to content

Instantly share code, notes, and snippets.

View Dictionary sort.py
# sort dictionary by value
>>> sorted(d.iteritems(), key=itemgetter(1), reverse=True)
[('b', 23), ('d', 17), ('c', 5), ('a', 2), ('e', 1)]
# sort dict by keys:
>>> sorted(d, key=d.__getitem__, reverse=True)
['b', 'd', 'c', 'a', 'e']
# Also, Python 2.5's heapq.nlargest() function addresses the common use