Introduction
A dictionary in Python is a collection of key-value pairs, where each key is unique. Sometimes, you might want to sort these dictionaries based on their values rather than their keys. Sorting a dictionary by value can help you analyze data more effectively.

This article will guide you through different methods to sort a dictionary by its values in Python, with simple examples and explanations.
Methods to Sort a Dictionary by Value
Using sorted() Function
The sorted() function can be used to sort a dictionary by its values. The sorted() function returns a sorted list of the specified iterable's items.
Syntax
sorted(iterable, key=None, reverse=False)
- iterable: The sequence to be sorted.
- key: A function that serves as a key for the sort comparison.
- reverse: A Boolean. If True, the sorted list is reversed.
Example
Output
Sorted Dictionary: {'banana': 5, 'cherry': 7, 'apple': 10}
In this example, the dictionary is sorted by its values in ascending order using a lambda function as the key.
Sorting in Ascending and Descending Order
You can sort a dictionary in both ascending and descending order.
Ascending Order
Output:
Ascending Order: {'banana': 5, 'cherry': 7, 'apple': 10}Descending Order
Output
Descending Order: {'apple': 10, 'cherry': 7, 'banana': 5}
In the descending order example, the reverse=True argument is added to sort the values in descending order.
Using For Loop
You can sort a dictionary by its values using a for loop by iterating over the dictionary and sorting the key-value pairs manually.
Output
Sorted dictionary by value: {'orange': 5, 'apple': 10, 'grape': 15, 'banana': 20}
Using Bubble Sort
Bubble Sort is a simple sorting algorithm that repeatedly compares adjacent items and swaps them if they are in the wrong order. To sort a dictionary by value, we can implement Bubble Sort on its items.
Output
Sorted dictionary by value using Bubble Sort: {'orange': 5, 'apple': 10, 'grape': 15, 'banana': 20}
Using item getter from the operator Module
Another way to sort a dictionary by value is by using itemgetter from the operator module.
Syntax
operator.itemgetter(n)
Example
Output
Sorted Dictionary: {'banana': 5, 'cherry': 7, 'apple': 10}
In this example, itemgetter(1) is used to sort the dictionary by its values.
Handling Ties in Values
When sorting by values, ties (identical values) may occur. The default behavior is to retain the original order of keys with identical values.
Example
Output
Sorted Dictionary with Ties: {'banana': 5, 'cherry': 7, 'date': 7, 'apple': 10}Sorting Nested Dictionaries
Sometimes dictionaries contain other dictionaries as values. Sorting these can be a bit more complex but follows the same principles.
Example
Output
Sorted Nested Dictionary: {'fruits': {'banana': 5, 'apple': 10}, 'vegetables': {'carrot': 3, 'beetroot': 8}}



