2

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?

Anshul Goyal
  • 119
  • 10
  • 3
    Does this answer your question? [Sort list of lists ascending and then descending](https://stackoverflow.com/questions/6666748/sort-list-of-lists-ascending-and-then-descending) – Mihai Alexandru-Ionut Oct 30 '20 at 12:26

1 Answers1

3

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}]

KiraLT
  • 2,385
  • 1
  • 24
  • 36