Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

two level sorting of a list of dictionaries in python

Tags:

python

sorting

I have a list of dictionaries as follows:

 {"id": 1, "score": some_score.. othe values}
 {"id": 1, "score": some_differetscore.. othe values}  
 {"id": 22, "score": some_score.. othe values}
 {"id": 3, "score": some_score.. othe values}

What I am hoping to get is to iterate thru this list in such a way that it is sorted as follows.

The list is sorted by "id" and then reverse sorted with "score"

So all the entries with "id" 1 are clubbed together and then the entry with the topmost score is at the top?? How do i do this?

Thanks

like image 581
frazman Avatar asked Jan 30 '26 07:01

frazman


1 Answers

Try this:

sorted(mylist, key=lambda d: (d["id"], -d["score"]))
like image 56
nneonneo Avatar answered Feb 01 '26 19:02

nneonneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!