Table of Contents
A dictionary is a very commonly used data structure in Python due to its flexibility for storing and managing data as key-value pairs. Now, what happens when you need to organize (or sort) the data stored in a dictionary based on its values—like ranking users by scores, filtering top-selling products, or analyzing word frequencies? Dictionaries in Python do not maintain order based on values, making sorting necessary when working with ranked data.
In this article, we will learn how to sort dictionaries by value using Python’s built-in tools. Whether you’re preparing data for visualization, building a leaderboard, or optimizing workflows, mastering this skill will streamline your coding projects. We’ll break down the process step-by-step, provide clear examples, and explore real-world scenarios where sorting dictionaries unlock powerful insights.
What is a Dictionary in Python?
A dictionary in Python is a built-in data structure that stores data as key-value pairs. Think of it like a real-life dictionary: you look up a word (the key) to find its definition (the value).
Dictionaries are:
- Unordered (in Python 3.6 and earlier; insertion order is preserved in Python 3.7+).
- Mutable (can be changed after creation).
- Accessed via keys, not numerical indexes.
Let’s look at an example:
student_grades = {
"Alice": 92,
"Bob": 85,
"Charlie": 78,
"Diana": 95
}
Here, the keys are student names (strings), and values are their grades (integers).
To learn more about the dictionary data structure, check out this comprehensive guide in Python’s official documentation.
How to Sort a Dictionary by Value (Step-by-Step)
Before I show you how to do the sorting, let’s quickly talk about what sort by value even means.
Sorting a dictionary by value means rearranging its key-value pairs based on the values instead of the keys. For example, sorting student_grades
by grades (values) would arrange the students from lowest to highest score (or vice versa).
Step 1: Create a Sample Dictionary
fruits = {"apple": 5, "banana": 2, "cherry": 8, "date": 3}
Step 2: Use sorted()
to Sort by Value
The sorted()
function returns a sorted list of the dictionary’s key-value pairs (as tuples). Use the key
parameter to specify sorting by the second element of each tuple (the value).
Ascending Order (Low to High):
sorted_items = sorted(fruits.items(), key=lambda x: x[1])
# sorted_items is a list: [('banana', 2), ('date', 3), ('apple', 5), ('cherry', 8)]
Descending Order (High to Low):
sorted_items = sorted(fruits.items(), key=lambda x: x[1], reverse=True)
# Result: [('cherry', 8), ('apple', 5), ('date', 3), ('banana', 2)]
Step 3: Convert the Sorted List Back to a Dictionary
sorted_dict = dict(sorted_items)
print(sorted_dict)
# Output (ascending): {'banana': 2, 'date': 3, 'apple': 5, 'cherry': 8}
Output:
Ascending: {'banana': 2, 'date': 3, 'apple': 5, 'cher ry': 8}
Descending: {'cherry': 8, 'apple': 5, 'date': 3, 'banana': 2}
Use Cases for Sorting Dictionaries by Value
Let’s look at some examples of where you can benefit from sorting a dictionary by value.
- Leaderboards in Games: Sort player scores to display rankings.
Example:{"Player1": 1200, "Player2": 1500}
→ Highest score first. - Word Frequency Analysis: Identify the most common words in a text.
Example:{"the": 45, "apple": 12}
→ Sort by counts. - Stock Price Tracking: Sort stocks by their current price.
Example:{"AAPL": 180, "GOOGL": 2700}
→ Cheapest first. - Student Grading: Rank students by exam scores.
Example:{"Alice": 92, "Bob": 85}
→ Highest grades first.
Key Takeaways
- Use
sorted(dict.items(), key=lambda x: x[1])
to sort by values. - Convert the sorted list back to a dictionary with
dict()
. - Python 3.7+ preserves insertion order, so the sorted dictionary maintains the new order.
By mastering this technique, you can efficiently organize data for analysis, reporting, or user-facing features!
Related Reading: