sorting using keys in python.

Tue 26 February 2008 | tags: python

I’ve used comparator functions while sorting in python quite often. I had a complex object today that i had to sort on using non-standard comparator functions.

My object was a dictionary that contained a list of 2 dictionaries that in turn containd lists of objects. I wanted to sort the first dictinary based on the len() of the objects of the lists at the other end of the hierarchy.

using a cmp function i had to do something like:

def comparator(x,y):
#4 lines do stuff to get the len() of data inside x

#4 lines do stuff to get the len() of data inside y

if len_x > len_y:
return 1
elif len_x == len_y:
return 0
return -1


However i came upon the sorting howto on and a way to do sorting that i did not know. Using the key funciton.

Instead of sorted(iterable,cmp=my_cmp_func) you can do sorted(iterable,key=my_key_func).

my_key_func is called with each element of the iterable as argument. It must returns a value that is used in sorting (I assume using standard cmp).

This meant that instead of my cmp function i could do only:

def my_key_func(x):
#4 lines do stuff to get the len() of data inside x
return len_x


It makes more sense because basically we are not sorting x and y based on their own value, but we are sorting x and y based on some remote data connected to x and y.

Certainly nicer.

Comments !