Skip to content
Advertisement

How to get a list of dictionaries sorted by three criteria

I want to get a list sorted accordingly to the following rules persons.sort(key = lambda p: (abs(p["height"] - 180), p["weight"]==75, p["weight"])) i.e. I need it to get sorted firstly by its closeness to the height 180, then all of the weight values which are equal to 75, and then I want them to be sorted ascendingly by its weight…

I came up with the following code, which is not working…

JavaScript

For the following sample data, for instance,

JavaScript

I need to get the list sorted as such:

JavaScript

Advertisement

Answer

This is happening because False is a lower value than True. Use

JavaScript

changing the comparison for the “weight” key.

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