Python sorts the dict by value, creating a list, how to sort it from largest to smallest?

I read a few posts on how to sort a dict in python, the problem is that the solution I found doesn't sort the dict in the correct order. I found this

results = sorted(results.items(), key=lambda x: x[1])

This creates a list of key pairs, values ​​sorted from smallest to largest, I would like to move from the largest to the smallest. Is there an easy fix here?

+4
source share
1 answer

Turn over the list:

results = sorted(results.items(), key=lambda x: x[1])
results.reverse()

or even better:

results = sorted(results.items(), key=lambda x: x[1], reverse=True)

or better:

results = sorted(results.items(), cmp=lambda a,b: b[1]-a[1])

Oddly enough, the first option is the fastest:

In [48]: %timeit sorted(x.items(), key=lambda x: x[1]).reverse()
100000 loops, best of 3: 2.93 us per loop

In [49]: %timeit sorted(x.items(), key=lambda x: x[1], reverse=True)
100000 loops, best of 3: 3.24 us per loop

In [50]: %timeit sorted(x.items(), cmp=lambda a,b: b[1]-a[1])
100000 loops, best of 3: 3.11 us per loop
+4
source

Source: https://habr.com/ru/post/1532576/


All Articles