2011年8月9日 星期二

Sort dictionary by value

For example, given an occurrence count of:

>>> d = {'a':2, 'b':23, 'c':5, 'd':17, 'e':1}

we might do:

>>> items = [(v, k) for k, v in d.items()]
>>> items.sort()
>>> items.reverse() # so largest is first
>>> items = [(k, v) for v, k in items]

resulting in:

>>> items
[('b', 23), ('d', 17), ('c', 5), ('a', 2), ('e', 1)]

Reference

沒有留言: