Monday, August 20, 2012

Sorting dictionaries in python


Suppose we want to sort a dictionary based on its value, or a list of tuples based on some arbituary key.

Easy as a pie, just use itemgetter() function from operator:


>>> student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
>>> from operator import itemgetter
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]


More examples are here:
http://wiki.python.org/moin/HowTo/Sorting