Skip to content
Advertisement

How to sort objects by multiple keys?

Or, practically, how can I sort a list of dictionaries by multiple keys?

I have a list of dicts:

JavaScript

and I need to use a multi key sort reversed by Total_Points, then not reversed by TOT_PTS_Misc.

This can be done at the command prompt like so:

JavaScript

But I have to run this through a function, where I pass in the list and the sort keys. For example, def multikeysort(dict_list, sortkeys):.

How can the lambda line be used which will sort the list, for an arbitrary number of keys that are passed in to the multikeysort function, and take into consideration that the sortkeys may have any number of keys and those that need reversed sorts will be identified with a ‘-‘ before it?

Advertisement

Answer

This answer works for any kind of column in the dictionary — the negated column need not be a number.

JavaScript

You can call it like this:

JavaScript

Try it with either column negated. You will see the sort order reverse.

Next: change it so it does not use extra class….


2016-01-17

Taking my inspiration from this answer What is the best way to get the first item from an iterable matching a condition?, I shortened the code:

JavaScript

In case you like your code terse.


Later 2016-01-17

This works with python3 (which eliminated the cmp argument to sort):

JavaScript

Inspired by this answer How should I do custom sort in Python 3?

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement