How to Sort a Dictionary by Value in Python?

As a data scientist working on a project, I recently faced a challenge where I needed to analyze sales data stored in a dictionary format. To gain meaningful insights, it was crucial to sort the dictionary by the sales values. In this tutorial, I will explain how to sort a dictionary by value in Python. I will walk you through the process of sorting a dictionary by value using Python, providing detailed examples.

Sort a Dictionary by Value in Python

Before getting into sorting, let’s quickly recap what dictionaries are in Python. A dictionary is an unordered collection of key-value pairs, where each key is unique. It allows you to store and retrieve data efficiently based on keys. Here’s an example of a dictionary containing sales data for different states in the USA:

sales_data = {
    "California": 25000,
    "Texas": 20000,
    "New York": 30000,
    "Florida": 22000
}

Python provides several ways to sort a dictionary by value. Let’s explore the most common approaches:

Read How to Update Values in a Python Dictionary?

1. Use the sorted() Function

The sorted() function in Python is a built-in function that returns a new sorted list from an iterable. When used with a dictionary, it sorts the dictionary based on its keys by default. However, we can customize the sorting behavior by providing a key function.

To sort a dictionary by value, we can use the sorted() function in combination with a lambda function that extracts the values from the dictionary. Here’s an example:

sorted_sales_data = dict(sorted(sales_data.items(), key=lambda x: x[1]))
print(sorted_sales_data)

Output:

{'Texas': 20000, 'Florida': 22000, 'California': 25000, 'New York': 30000}

You can look at the screenshot below to see the output.

Sort a Dictionary by Value in Python

In this code, we use sales_data.items() to get a list of key-value pairs from the dictionary. Then, we pass a lambda function lambda x: x[1] as the key function to sorted(), which extracts the value (second element) from each key-value pair. Finally, we convert the sorted list of key-value pairs back into a dictionary using the dict() constructor.

Check out How to Change a Key in a Dictionary in Python?

2. Use the itemgetter Function

Another approach to sorting a dictionary by value is to use the itemgetter function from the operator module. It allows you to create a callable object that retrieves a specific element from an iterable. Here’s an example:

from operator import itemgetter

sorted_sales_data = dict(sorted(sales_data.items(), key=itemgetter(1)))
print(sorted_sales_data)

Output:

{'Texas': 20000, 'Florida': 22000, 'California': 25000, 'New York': 30000}

You can look at the screenshot below to see the output.

How to Sort a Dictionary by Value in Python

In this case, we import the itemgetter function from the operator module and pass 1 as the argument to specify that we want to sort based on the second element (value) of each key-value pair.

Read Write a Python Program to Remove Duplicates From a Dictionary

Sort in Descending Order

By default, the sorting happens in ascending order. However, you may want to sort the dictionary by value in descending order. To achieve this, you can simply add the reverse=True parameter to the sorted() function. Here’s an example:

sorted_sales_data = dict(sorted(sales_data.items(), key=lambda x: x[1], reverse=True))
print(sorted_sales_data)

Output:

{'New York': 30000, 'California': 25000, 'Florida': 22000, 'Texas': 20000}

You can look at the screenshot below to see the output.

Sort a Dictionary by Value in Python in Descending Order

Now the dictionary is sorted by value in descending order, with the highest sales value appearing first.

Check out How to Remove Multiple Keys from a Dictionary in Python?

Deal with Duplicate Values

When sorting a dictionary by value, it’s important to consider the possibility of duplicate values. In such cases, the order of keys with the same value may not be preserved. If you need to maintain a specific order for keys with duplicate values, you can use a stable sorting algorithm.

Python’s built-in sorted() function uses a stable sorting algorithm called Timsort, which preserves the relative order of elements with equal values. Here’s an example:

sales_data = {
    "California": 25000,
    "Texas": 20000,
    "New York": 30000,
    "Florida": 25000
}

sorted_sales_data = dict(sorted(sales_data.items(), key=lambda x: x[1]))
print(sorted_sales_data)

Output:

{'Texas': 20000, 'California': 25000, 'Florida': 25000, 'New York': 30000}

In this case, both “California” and “Florida” have the same sales value of 25000. The sorting preserves their relative order, with “California” appearing before “Florida” in the sorted dictionary.

Read How to Save Python Dictionary to a CSV File?

Conclusion

In this tutorial, I explained how to sort a dictionary by value in Python. We explored different approaches to accomplish this, including using the sorted() function with lambda expressions and the itemgetter() function from the operator module. I also discussed how to sort in descending order and deal with duplicate values.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.