← Back to Articles
Tutorial

Sort Dictionary by Value in Python

Learn how to sort dictionaries by value in Python with examples.

Sorting a dictionary by value in Python is a common task that can be accomplished using various methods. This operation is crucial when you need to organize data in a specific order.

One of the most popular methods to sort a dictionary by value is using the sorted() function. This function takes a dictionary and returns a list of tuples sorted by the specified criteria. For instance, you can use lambda functions to specify that you want to sort by the dictionary's values.

When sorting dictionaries by value, it is important to consider the data type of the values. Ensure that the values are comparable, such as integers or strings, to avoid errors. Additionally, decide whether you need an ascending or descending order as this will affect the sorting logic.

A common mistake is trying to sort a dictionary directly without converting it to a list of tuples or another data structure first. Remember that dictionaries themselves are unordered collections, so sorting must be performed on a derived structure.

Code Examples

Example 1

my_dict = {'apple': 10, 'banana': 5, 'cherry': 7}
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_dict)

Example 2

my_dict = {'apple': 10, 'banana': 5, 'cherry': 7}
sorted_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[1], reverse=True)}
print(sorted_dict)

More Python Tutorials