How to sort objects by multiple keys?

This article has a nice rundown on various techniques for doing this. If your requirements are simpler than “full bidirectional multikey”, take a look. It’s clear the accepted answer and the blog post I just
referenced influenced each other in some way, though I don’t know which order.

In case the link dies here’s a very quick synopsis of examples not covered above:

mylist = sorted(mylist, key=itemgetter('name', 'age'))
mylist = sorted(mylist, key=lambda k: (k['name'].lower(), k['age']))
mylist = sorted(mylist, key=lambda k: (k['name'].lower(), -k['age']))

Leave a Comment