Sort a Dictionary by Value in Ascending or Descending Order in Python

Sorting a dictionary by value allows you to arrange the key-value pairs in a specific order based on the values. In this blog post, we will explore different methods to sort a dictionary by value in ascending or descending order in Python.

Method 1: Using the sorted() function with a lambda function

Python

Output:

Ascending Order: {‘b’: 5, ‘a’: 10, ‘d’: 15, ‘c’: 20}
Descending Order: {‘c’: 20, ‘d’: 15, ‘a’: 10, ‘b’: 5}

Method 2: Using the operator module

Python

Output:

Ascending Order: {‘b’: 5, ‘a’: 10, ‘d’: 15, ‘c’: 20}
Descending Order: {‘c’: 20, ‘d’: 15, ‘a’: 10, ‘b’: 5}