KDecker
KDecker

Reputation: 7128

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?

Upvotes: 5

Views: 5761

Answers (1)

ebarr
ebarr

Reputation: 7842

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

Upvotes: 4

Related Questions