Skip to main content
HomeTutorialsPython

How to Sort a Dictionary by Value in Python

Learn efficient methods to sort a dictionary by values in Python. Discover ascending and descending order sorting and bonus tips for key sorting.
Jun 2024  · 5 min read

Sorting is a fundamental operation in data manipulation, and dictionaries in Python are no exception. Whether we're working on a complex data analysis project or a simple script, understanding how to efficiently sort a dictionary by value can be immensely useful.

In this article, we break down the various methods to sort dictionaries by their values in Python, ensuring we have the tools to organize our data as needed.

The Short Answer: How to Sort a Dictionary by Value in Python

To quickly sort a dictionary by value, we can use Python's built-in .sorted() function in combination with a lambda function. This method is straightforward and efficient for most use cases.

student_scores = {
    'Alex': 88,
    'Ben': 75,
    'Cyrus': 93,
    'Denver': 85
}
sorted_by_values = dict(sorted(student_scores.items(), key=lambda item: item[1]))
{'Ben': 75, 'Denver': 85, 'Alex': 88, 'Cyrus': 93}

Now, let's take a step back and understand Python dictionaries and why we might need to sort them.

What Are Python Dictionaries?

Python dictionaries are a type of data structure that stores data in key-value pairs. They are highly versatile and allow fast lookups, insertions, and deletions. Here’s a simple example:

student_scores = {
    'Alex': 88,
    'Ben': 75,
    'Cyrus': 93,
    'Denver': 85
}

In the dictionary above, the students' names are the keys, and their scores are the values. 

Dictionaries are helpful in many scenarios, such as when we need to store and retrieve data efficiently. However, there are times when sorting this data by values rather than by keys becomes necessary—for instance, when we want to rank students by their scores.

How to Sort a Dictionary by Value in Python

Now, let’s take a closer look at the .sorted() function in Python and how to use it specifically for sorting dictionaries by value.

How to sort a dictionary by value using .sorted()

The .sorted() function is a powerful and flexible tool for sorting in Python. To sort a dictionary by its values, we can use a lambda function to specify that the sorting should be based on the dictionary’s values.

student_scores = {
    'Alex': 88,
    'Ben': 75,
    'Cyrus': 93,
    'Denver': 85
}
sorted_by_values = dict(sorted(student_scores.items(), key=lambda item: item[1]))
print(sorted_by_values)
{'Ben': 75, 'Denver': 85, 'Alex': 88, 'Cyrus': 93}

In this example, student_scores.items() returns a view object that displays a list of the dictionary's key-value tuple pairs. The .sorted() function sorts these pairs by the values (item[1]), and dict() converts the sorted list back into a dictionary.

How to sort a dictionary by value in descending or ascending order

By default, the .sorted() function sorts in ascending order. However, depending on the situation, we can easily modify this to sort in descending or ascending order by setting the reverse parameter to True or False.

How to sort a dictionary in ascending order

As mentioned, a dictionary will be sorted in ascending order by default when using the .sorted() function. We can also achieve ascending order by setting the reverse parameter to False.

sorted_by_values_asc = dict(sorted(student_scores.items(), key=lambda item: item[1], reverse=False))
print(sorted_by_values_asc)
{'Ben': 75, 'Denver': 85, 'Alex': 88,  'Cyrus': 93}

How to sort a dictionary in descending order

If we want to sort in ascending order, we can set the reverse parameter to True.

sorted_by_values_desc = dict(sorted(student_scores.items(), key=lambda item: item[1], reverse=True))
print(sorted_by_values_desc)
{'Cyrus': 93, 'Alex': 88, 'Denver': 85, 'Ben': 75}

Bonus: How to Sort a Dictionary by Key in Python

While this article focuses on sorting by values, it's also helpful to know how to sort a dictionary by its keys. This can be done similarly using the .sorted() function.

sorted_by_keys = dict(sorted(student_scores.items()))
print(sorted_by_keys)
{'Alex': 88, 'Ben': 75, 'Cyrus': 93, 'Denver': 85}

For descending order, simply set reverse=True:

sorted_by_keys_desc = dict(sorted(student_scores.items(), reverse=True))
print(sorted_by_keys_desc)
{'Denver': 85', 'Cyrus': 93, 'Ben': 75, 'Alex': 88}

Conclusion

Sorting a dictionary by its values in Python is a common task that can be accomplished easily using the .sorted() function. Whether we need the data in ascending or descending order, understanding these techniques will make our data manipulation tasks more straightforward and more efficient. By mastering these sorting methods, we can ensure our data is consistently organized to suit our needs best.

FAQs

Q1: Can I sort a dictionary by values if the values are strings instead of numbers?

A1: Yes, we can sort a dictionary by values, even if the values are strings. The .sorted() function will sort the values alphabetically in ascending or descending order, just as it does with numbers.

Q2: How can I sort a dictionary by values if it contains nested dictionaries?

A2: To sort a dictionary with nested dictionaries, we need to define a custom sorting function that extracts and compares the relevant nested values. This requires a more complex lambda function or a separate function to handle the comparison.

Q3: Can I sort a dictionary by values in-place without creating a new dictionary?

A3: No, dictionaries in Python are inherently unordered collections as of versions before 3.7, and even though they maintain insertion order from Python 3.7 onwards, there is no built-in method to sort them in-place. Sorting a dictionary always results in creating a new dictionary with the desired order.

Q4: What is the time complexity of sorting a dictionary by values in Python?

A4: The time complexity of sorting a dictionary by values using the .sorted() function is O(n log n), where n is the number of key-value pairs in the dictionary. This is because .sorted() internally uses Timsort, a hybrid sorting algorithm with this complexity.

Q5: Will sorting a dictionary by values change the original dictionary?

A5: No, sorting a dictionary by values using the .sorted() function creates a new dictionary. The original dictionary remains unchanged.


Photo of Neetika Khandelwal
Author
Neetika Khandelwal
I am a Java developer and an accomplished technical writer specializing in data science, artificial intelligence (AI), and Java programming. With over 3+ years of experience in software development, I have honed a good expertise in making robust, scalable applications and leveraging Java’s versatility to solve complex problems. I am passionate about sharing knowledge with the broader tech community. Through comprehensive technical articles, tutorials, and guides, I try to demystify intricate data science and AI topics, making them accessible to beginners and experienced professionals. Currently, I have over 125+ blogs published.
Topics

Learn more about Python with these courses!

Course

Introduction to Python

4 hr
5.6M
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

tutorial

Sorting in Python Tutorial

Discover what the sort method is and how to do it.
DataCamp Team's photo

DataCamp Team

1 min

tutorial

Python Dictionary Tutorial

In this Python tutorial, you'll learn how to create a dictionary, load data in it, filter, get and sort the values, and perform other dictionary operations.
DataCamp Team's photo

DataCamp Team

14 min

tutorial

Pandas Sort Values Tutorial

Learn how to sort rows of data in a pandas Dataframe using the .sort_values() function.
DataCamp Team's photo

DataCamp Team

4 min

tutorial

Python Dictionaries Tutorial: The Definitive Guide

Learn all about the Python Dictionary and its potential. You will also learn how to create word frequency using the Dictionary.
Aditya Sharma's photo

Aditya Sharma

6 min

tutorial

Python Dictionaries Tutorial

Learn how to create a dictionary in Python.
DataCamp Team's photo

DataCamp Team

3 min

tutorial

Python Tutorial for Beginners

Get a step-by-step guide on how to install Python and use it for basic data science functions.
Matthew Przybyla's photo

Matthew Przybyla

12 min

See MoreSee More