Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sort a dict by values, producing a list, how to sort this from largest to smallest?

I have read a few posts now on how to sort a dict in python, the problem is that the solution that I have found does not sort the dict in the right order. What I have found is this

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

This produces a list of key,value pairs sorted from smallest to largest, I would like to go from largest to smallest. Is there any easy fix here?

like image 983
KDecker Avatar asked Oct 01 '22 06:10

KDecker


1 Answers

Reverse 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 best:

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

Although 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
like image 94
ebarr Avatar answered Oct 20 '22 07:10

ebarr