Skip to content

Python sort dict by value descending | Example code

  • by

Use the operator itemgetter method to sort dict by value descending in Python. operator.itemgetter(1) takes the value of the key which is at the index 1.

Example sort dict by value descending in Python

Simple example code. You have to import operator module to use the itemgetter method.

import operator

d = {"A": 2, "B": 4, "C": 3, "D": 1, "E": 0}

res = dict(sorted(d.items(), key=operator.itemgetter(1)))

print(res)

Output:

Python sort dict by value descending

Or use the reverse attribute

sorted_d = dict(sorted(d.items(), key=operator.itemgetter(1),reverse=True))

Or you can use the sorted() function along with a lambda function as the key parameter. Here’s an example:

my_dict = {'a': 3, 'b': 1, 'c': 2}

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

print(sorted_dict)

In the code above, my_dict is the original dictionary. The sorted() function is used with the key parameter set to a lambda function that takes each key-value pair (x) and returns the value (x[1]). The reverse=True argument is passed to sort the dictionary in descending order. Finally, the dict() function is used to convert the sorted list of tuples back into a dictionary.

As a result, sorted_dict contains the sorted dictionary in descending order based on the values.

Do comment if you have any doubts or suggestions on this Python dict topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading