Thursday, July 19, 2007

Python Tip of the Day

Have you ever wanted to sort the keys of a python dictionary by their values?

I wish I could take credit, but the credit must go to my dear friend AquaRapid. Check out this pythonic goodness:

[ x[0] for x in sorted(dictionaryToSortByKeyValues.items(),
lambda x, y: cmp(x[1], y[1])) ]

1 comments:

Hoyt said...

Nice page, well done.

What about:

from operator import itemgetter

[k for k, v in sorted(d.iteritems(), key=itemgetter(1))]

A timing comparison on a dictionary of 100000 items gives 0.67 seconds for this and 2.1 seconds for the one above. The additional function calls via the lambda function introduces a bit of overhead... Just a thought.