Python: Sorting a List of Objects or Dictionaries by Multiple Keys Bidirectionally

Tue 15 Feb 2011 by in Web Design & Development

Tags: python

Basic Sorting

The above methods for sorting a list of dictionary objects is very common and suitable for sorting lists containing dictionaries or objects. sorted also allows your key function to return a tuple of values if you wish to sort your list by more than one key like so:

Sorting by Multiple Keys

Bidirectional Sorting with Numeric Values

Sorting by multiple keys bidirectionally is simple when dealing with numeric values.

Bidirectional Sorting

Sorting bidirectionally with non numeric values gets a little more involved. The following two short functions will allow us to do exactly what we want.

And here are a few examples of them in use: