Sort List of dicts first in ascending order of a key and then in descending order of another key

Viewed 86

I have a list of dicts like this:

[{"x" : 5 , "y" : 7} , {"x" : 4 , "y" : 3} , {"x" : 4 , "y" : 7}]

I want to sort them first in ascending order of x and then in descending order of y so that the result is

[{"x" : 4 , "y" : 7} , {"x" : 4 , "y" : 3} , {"x" : 5 , "y" : 7}]

I can sort both in ascending order by

sorted(a , key=lambda k: (k['x'] , k['y']))

or in descending order by

sorted(a , key=lambda k: (k['x'] , k['y']) , reverse=True)

Is there a good way to sort by x ascending and y descending here?

1 Answers

If you are sorting by number, you can just multiply by -1 to reverse the order:

>>> a = [{"x" : 5 , "y" : 7} , {"x" : 4 , "y" : 3} , {"x" : 4 , "y" : 7}]
>>> sorted(a , key=lambda k: (k['x'] , k['y'] * -1))
[{'x': 4, 'y': 7}, {'x': 4, 'y': 3}, {'x': 5, 'y': 7}]

You can also add - before the variable and it will work the same way as multiplying by -1:

>>> sorted(a , key=lambda k: (k['x'] , -k['y']))
[{'x': 4, 'y': 7}, {'x': 4, 'y': 3}, {'x': 5, 'y': 7}]

Related