+1 vote
in Programming Languages by (74.7k points)
I want to sort the dictionary in descending order of its values. How can I do it in a Pythonic way? Is there any function for it?

1 Answer

+3 votes
by (13.2k points)
selected by
 
Best answer

To sort a Python dictionary by its values, you can use the sorted() function along with a lambda function to specify that the sorting should be based on the dictionary values. If you want to sort the dictionary by values in descending order, you can pass the "reverse=True" parameter to the sorted() function. The "reverse=False" parameter will sort in ascending order of values. The default value of this parameter is False, so if you do not mention "reverse=False", it will sort in ascending order by default.

Here is an example:

>>> aa={'a':123, 'b':323, 'c':123, 'd':123, 'e':453, 'f':56}

>>> aa

{'a': 123, 'b': 323, 'c': 123, 'd': 123, 'e': 453, 'f': 56}

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

{'e': 453, 'b': 323, 'a': 123, 'c': 123, 'd': 123, 'f': 56}

>>> dict(sorted(aa.items(), key=lambda item: item[1], reverse=False))

{'f': 56, 'a': 123, 'c': 123, 'd': 123, 'b': 323, 'e': 453}


...