Tuesday, 19th October 2010
Sorting lists in Python is very simple (
list.sort()), but I often need to sort a list of objects based on the one of the objects' attributes. I tried various messy, hacky methods before finding a simple method: passing a new comparison function for
sort to use.
Say you have a list of objects, each of which has an attribute called 'score'. You can sort the list by object score like so:
my_list.sort(key = lambda x: x.score)
This passes a lambda function to
sort, which tells it to compare the score attributes of the objects. Otherwise, the sort function works exactly as normal (so will, for example, order strings alphabetically.
You can also use this technique to sort a dictionary by its values:
sorted_keys = sorted(my_dict.keys(), key=lambda x: my_dict[x]) for k in sorted_keys: print my_dict[k]
The code creates a list of the dictionary keys, which it sorts based on the value for each key (note that you can't simply sort
my_dict.keys()). Alternatively you can loop through the keys and values in one go:
for k, v in sorted(my_dict.items(), key=lambda (k,v): v): print k, v