Fun Python Syntax – operator.itemgetter(), sorted(), and lambda functions – Oh MY!

This is perhaps the coolest idiom of Python I have seen yet. Thanks
to Clint for stopping by my office for a Python versus Perl versus PHP smackdown that got me thinking.

This is a great way to sort a list of tuples on the second key:

>>> import operator
>>> a = [ (1,'z'), (2, 'x'), (3, 'y') ]
>>> a.sort(key=operator.itemgetter(1))
>>> a
[(2, 'x'), (3, 'y'), (1, 'z')]
>>>

Pretty clever. The method name could be a bit shorter :)

Here is an operator free version using lamda

>>> a.sort(key=lambda x: x[1])
>>> a
[(2, 'x'), (3, 'y'), (1, 'z')]

And here is one that uses the second entry and the first entry:

>>> a.sort(key=lambda x: (x[1], x[0]) )
>>> a
[(2, 'x'), (3, 'y'), (1, 'z')]

And then the most super-duper fun one of all – sorting a dictionary:

>>> a = { "a": 9, "b" : 8, "c" : 7 }
>>> b = sorted(a.items())   # Sort by key
>>> b
[('a', 9), ('b', 8), ('c', 7)]
>>> >>> c = sorted(a.items(),key=lambda x: x[1])  # By value
>>> c
[('c', 7), ('b', 8), ('a', 9)]
>>> c = sorted(a.items(),key=lambda x: x[1], reverse=True)  # By Value Backwards
>>> c
[('a', 9), ('b', 8), ('c', 7)]
>>> d = sorted(a.items(),key=lambda x: (x[1], x[0]), reverse=True)  # Value then Key
>>> d
[('a', 9), ('b', 8), ('c', 7)]
>>>

Time to go put this in my Python book in Chapter 10 (www.py4inf.com). Too bad it did not make it into version 0.0.2 printed copies – but it will make it into the Chapter 10 lecture slides!

More fun tricks at: http://wiki.python.org/moin/HowTo/Sorting