Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multisort list of dictionaries in Python? [duplicate]

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) ) ?

like image 363
Bdfy Avatar asked Nov 24 '15 12:11

Bdfy


2 Answers

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.

like image 77
thefourtheye Avatar answered Oct 15 '22 16:10

thefourtheye


As simple as:

from operator import itemgetter

>>> result = sorted(test, key=itemgetter('-ratio'))
>>> result = sorted(result, key=itemgetter('delta'))
like image 36
Diogo Martins Avatar answered Oct 15 '22 16:10

Diogo Martins