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