Skip to content

Python sort dict by value descending | Example code

  • by

Use 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 itemgetter method.

import operator

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

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



Python sort dict by value descending

Or use reverse attribute

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

Do comment if you have any doubts and 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

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.