Course
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]))
print(sorted_by_values)
# Expected output:
# {'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
}
# No expected output
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)
# Expected output:
# {'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)
# Expected output:
# {'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)
# Expected output:
# {'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)
# Expected output:
# {'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)
# Expected output:
# {'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.

