Question
I have a Python dictionary built from two database fields: one string field and one numeric field. The string field is unique, so I use it as the dictionary key.
I know how to sort by the dictionary keys, but how can I sort by the dictionary values instead?
I would like to sort the dictionary values in either ascending or descending order.
For example, imagine a dictionary like this:
scores = {
"alice": 82,
"bob": 95,
"carol": 78
}
How can I sort this dictionary based on the numeric values rather than the keys?
I have already seen approaches that use a list of dictionaries, but I do not really need that structure. I would like to know whether there is a simpler way to sort a normal dictionary by value.
Short Answer
By the end of this page, you will understand how to sort a Python dictionary by its values, how ascending and descending sorting work, why sorted() is commonly used, and how to turn the result into either a list of key-value pairs or a new ordered dictionary-like result.
Concept
In Python, a dictionary stores data as key-value pairs. For example:
prices = {
"apple": 2.5,
"banana": 1.2,
"orange": 3.0
}
Here:
- the keys are
"apple","banana", and"orange" - the values are
2.5,1.2, and3.0
When you want to sort a dictionary by value, you are really sorting its key-value pairs using the value part as the sorting rule.
A key idea is that dictionaries themselves are not sorted by value automatically. Instead, you usually do one of these:
- get a sorted list of
(key, value)tuples - build a new dictionary from that sorted result
The most common tool for this is Python's built-in sorted() function.
Why this matters
Sorting by value is useful when:
- ranking users by score
- ordering products by price
- showing most common words by count
Mental Model
Think of a dictionary like a set of labeled cards:
- the label on the card is the key
- the number written on it is the value
Example:
alice -> 82bob -> 95carol -> 78
If you sort by key, you arrange the cards by their labels: alice, bob, carol.
If you sort by value, you arrange the cards by the numbers written on them: 78, 82, 95.
So the dictionary is not being magically rearranged on its own. You are taking all the cards out, sorting them by the numeric part, and then optionally putting them back into a new dictionary in that order.
Syntax and Examples
The most common pattern is:
sorted(my_dict.items(), key=lambda item: item[1])
Example: sort by value ascending
scores = {
"alice": 82,
"bob": 95,
"carol": 78
}
sorted_scores = sorted(scores.items(), key=lambda item: item[1])
print(sorted_scores)
Output:
[("carol", 78), ("alice", 82), ("bob", 95)]
This returns a list of tuples, not a dictionary.
Example: sort by value descending
scores = {
"alice": 82,
"bob": 95,
"carol": 78
}
sorted_scores = sorted(scores.items(), key=lambda item: item[1], reverse=)
(sorted_scores)
Step by Step Execution
Consider this code:
scores = {
"alice": 82,
"bob": 95,
"carol": 78
}
result = sorted(scores.items(), key=lambda item: item[1])
print(result)
Step 1: scores.items()
This produces the dictionary's key-value pairs:
dict_items([('alice', 82), ('bob', 95), ('carol', 78)])
Each item is a tuple:
('alice', 82)('bob', 95)('carol', 78)
Step 2: sorted(...)
sorted() takes those pairs and sorts them.
Step 3: key=lambda item: item[1]
For each tuple, Python looks at , which is the value:
Real World Use Cases
Sorting a dictionary by value appears in many practical situations.
Ranking users by score
user_scores = {
"alice": 120,
"bob": 98,
"carol": 150
}
ranking = sorted(user_scores.items(), key=lambda item: item[1], reverse=True)
Useful for leaderboards and game stats.
Ordering products by price
product_prices = {
"keyboard": 49.99,
"mouse": 19.99,
"monitor": 199.99
}
cheapest_first = sorted(product_prices.items(), key=lambda item: item[1])
Useful in shopping apps and inventory scripts.
Sorting word frequencies
word_counts = {
"python": 15,
"code": 8,
"data": 22
}
most_common = sorted(word_counts.items(), key=lambda item: item[1], reverse=)
Real Codebase Usage
In real projects, developers often sort dictionary data after aggregation or validation.
Pattern: sort computed results
A common flow is:
- read data from a database or API
- build a dictionary of totals, counts, or scores
- sort by value for display or reporting
totals = {
"apples": 12,
"bananas": 7,
"oranges": 19
}
sorted_totals = sorted(totals.items(), key=lambda item: item[1], reverse=True)
Pattern: top N results
Often you do not need everything, only the highest or lowest values.
top_two = sorted(totals.items(), key=lambda item: item[1], reverse=True)[:2]
Pattern: guard clause before sorting
If data may be empty, developers often check first.
if not totals:
print("No data available")
else:
print(sorted(totals.items(), key= item: item[]))
Common Mistakes
Mistake 1: sorting the dictionary directly
Broken code:
scores = {"alice": 82, "bob": 95, "carol": 78}
print(sorted(scores))
This sorts the keys, not the values.
Output:
['alice', 'bob', 'carol']
Use this instead:
print(sorted(scores.items(), key=lambda item: item[1]))
Mistake 2: forgetting .items() when you need key-value pairs
Broken code:
scores = {"alice": 82, "bob": 95, "carol": 78}
print(sorted(scores, key=lambda item: item[1]))
Here, is each key string like , so means the second character of the string, not the dictionary value.
Comparisons
| Approach | Returns | Best when | Example |
|---|---|---|---|
sorted(d) | List of keys | You want keys in key order | sorted(scores) |
sorted(d.items(), key=lambda item: item[1]) | List of (key, value) tuples | You want full pairs sorted by value | sorted(scores.items(), key=lambda item: item[1]) |
dict(sorted(d.items(), key=lambda item: item[1])) | Dictionary | You want a dictionary in value-based insertion order | dict(sorted(...)) |
sorted(d, key=d.get) | List of keys |
Cheat Sheet
# Sort dictionary by value ascending
sorted(d.items(), key=lambda item: item[1])
# Sort dictionary by value descending
sorted(d.items(), key=lambda item: item[1], reverse=True)
# Convert sorted result back to dictionary
dict(sorted(d.items(), key=lambda item: item[1]))
# Get only keys sorted by value
sorted(d, key=d.get)
# Get only keys sorted by value descending
sorted(d, key=d.get, reverse=True)
Quick rules
d.items()gives(key, value)pairsitem[0]is the keyitem[1]is the valuesorted()returns a new listreverse=Truegives descending orderdict(...)can rebuild a dictionary from sorted pairs
Common patterns
FAQ
How do I sort a Python dictionary by value?
Use:
sorted(my_dict.items(), key=lambda item: item[1])
This sorts the key-value pairs by the value.
How do I sort a dictionary by value in descending order?
Add reverse=True:
sorted(my_dict.items(), key=lambda item: item[1], reverse=True)
Does sorted() change the original dictionary?
No. sorted() returns a new result and leaves the original dictionary unchanged.
Why does sorted(my_dict) sort keys instead of values?
Because iterating over a dictionary directly gives its keys. To sort by values, use .items() or key=my_dict.get.
How can I get only the keys sorted by value?
Use:
sorted(my_dict, key=my_dict.get)
Can I turn the sorted result back into a dictionary?
Mini Project
Description
Build a small leaderboard program that stores player names and scores in a dictionary, then prints the results sorted by score. This project demonstrates how to sort dictionary data by value, how to show ascending and descending results, and how to extract the top performers.
Goal
Create a Python script that sorts a dictionary of player scores by value and displays the full ranking plus the top player.
Requirements
Requirement 1 Requirement 2 Requirement 3
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.