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) ) ?
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: (-d['ratio'], d['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.
As simple as:
from operator import itemgetter
>>> result = sorted(test, key=itemgetter('-ratio'))
>>> result = sorted(result, key=itemgetter('delta'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With