Advanced Python Sorting Techniques

Using the python list sort method combined with lambda opens up a some nice sorting options.

Sorting by Day of Week

Lets say you have a list of dictionaries where one of the dictionary keys a string specifying a day of the week, such as ‘Monday’.

Since you can’t sort alphabetically, you must define a custom sort using a list and lambda as follows:

schedule = [ {'dayofweek' : 'Wednesday', 'task' : 'go to work' },
 {'dayofweek' : 'Friday', 'task' : 'go to beach' },
 {'dayofweek' : 'Friday', 'task' : 'day off' },
 {'dayofweek' : 'Monday', 'task' : 'meeting with client' } ]

# define a dictionary that will assign each weekday a sort order
convert = {'Monday' : 0, 'Tuesday' : 1, 'Wednesday' : 2, 'Thursday' : 3, 'Friday' : 4, 'Saturday' : 5, 'Sunday' : 6}

# use lambda to define a comparison function for sort to use when comparing two items
schedule.sort (lambda x, y : cmp (convert[x['dayofweek']], convert[y['dayofweek']]))

Sorting with a Secondary Key

Using the schedule list above, if we also want to sort by a secondary key task, the lambda function gets a little more complex:

schedule.sort (lambda x, y : cmp((convert[x['dayofweek']], x['task']), (convert[y['dayofweek']], y['task'])))