Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting dictionary descending in Python

I am new to Python and I was wondering if there is a more common way of sorting a dictionary in descending order than the way I'm doing it:

sorted_dictionary = sorted(dict.items(), key=lambda x: -x[1])
like image 742
Darien Avatar asked Feb 25 '16 10:02

Darien


3 Answers

There is a reverse option to sorted() you could use instead:

sorted(dict.items(), key=lambda kv: kv[1], reverse=True)

This produces the exact same output, and even works if the values are not numeric.

like image 152
Martijn Pieters Avatar answered Oct 14 '22 09:10

Martijn Pieters


This should work

{k: v for k, v in sorted(dict.items(), key=lambda item: item[1], reverse = True)}
like image 42
thereal90 Avatar answered Oct 14 '22 07:10

thereal90


Python dictionary aren't sortable. Your sorted_dictionary output is not a dictionary but a list. You have to use OrderedDict

from collections import OrderedDict

sorted_dictionary = OrderedDict(sorted(dict.items(), key=lambda v: v, reverse=True))
like image 35
Francesco Nazzaro Avatar answered Oct 14 '22 09:10

Francesco Nazzaro