Wednesday, July 29, 2009

Sorting Python Dictionary by Value

This is a slower version:

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


This is a faster version:

from operator import itemgetter
sorted(d.items(), key=itemgetter(1))


source: here

However, what if value is a list, and we would like to sort by the items inside the list?

For example, we have a dictionary variable x:
>>> x
{'a': [1, 2, 3], 'b': [0, 3, 1]}


We can sort them by the following command
>>> sorted(x.items(), key = (lambda k: k[0])) #sort by key
[('a', [1, 2, 3]), ('b', [0, 3, 1])]
>>> sorted(x.items(), key = (lambda k: k[1])) #sort by value
[('b', [0, 3, 1]), ('a', [1, 2, 3])]
>>> sorted(x.items(), key = (lambda k: k[1][0])) #sort by first item in value(a list)
[('b', [0, 3, 1]), ('a', [1, 2, 3])]
>>> sorted(x.items(), key = (lambda k: k[1][1])) #sort by second item in value(a list)
[('a', [1, 2, 3]), ('b', [0, 3, 1])]

No comments:

Post a Comment