Sorting list of dictionaries

You have a list of dictionaries and want to sort it based on one of the dictionary keys?

As quicksort is fairly general and easy to write, result is short and neat:

def quicksort(list, attribute):
	if len(list) <= 1:
		return list
	pivot = list.pop(0)
	greater_or_equal = quicksort([item for item in list if item[attribute] >= pivot[attribute]], attribute)
	lesser = quicksort([item for item in list if item[attribute] < pivot[attribute]], attribute)
	return lesser + [pivot] + greater_or_equal

Of course, this could be ugly threeliner, but readability counts. Also, on some data structures, You might consider another way of choosing pivot.

Functionalist might also like to itertools.chain().

Published on March 24, 2010 under beginners english programming python snippet