5

list have structure:

test = [{"title": title, "ratio": ratio, "delta": begin - now()}]

Need to sort by ratio ( max->min) and after sort by delta (min->max) ) ?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Bdfy
  • 23,141
  • 55
  • 131
  • 179

2 Answers2

9

You can use those two values of those two keys as representative of the current dictionary during the sorting's comparison.

sorted(test, key=lambda x: (-x['ratio'], x['delta']))

will sort them based on ratio's descending order first and if the values are equal, then delta's ascending order.


Here, we negate the value of d['ratio'], because by default, sorted does sort in ascending order. As we want the largest value of ratio to be at the beginning, we negate the value so that the biggest ratio will be treated as the smallest ratio. (For example out of 1, 10, and 100, after negating the values, -100 will be the smallest).

We want Python to use both the ratio and delta. So, we return the values of them in a tuple. When Python compares two dictionaries, it calls the key function with the dictionary objects as parameters and get two tuples and they will be compared to determine the smaller of the two. First, it compares the first elements of the tuples, if they are same, then the second elements will be compared.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
3

As simple as:

from operator import itemgetter

>>> result = sorted(test, key=itemgetter('-ratio'))
>>> result = sorted(result, key=itemgetter('delta'))
Diogo Martins
  • 917
  • 7
  • 15