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
- sorting statistics, totals, or measurements
In real programs, this happens often when data comes from databases, APIs, reports, or aggregations.
The core idea
If you call:
my_dict.items()
you get all key-value pairs. Then you can sort those pairs by telling Python to look at the second item in each pair, which is the value.
Example pair:
("alice", 82)
- index
0is the key - index
1is the value
So sorting by value usually means using something like key=lambda item: item[1].
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=True)
print(sorted_scores)
Output:
[("bob", 95), ("alice", 82), ("carol", 78)]
Example: convert back to a dictionary
In modern Python, dictionaries preserve insertion order, so you can build a new dictionary from the sorted pairs:
scores = {
"alice": 82,
"bob": 95,
"carol": 78
}
sorted_scores_dict = dict(sorted(scores.items(), key=lambda item: item[1]))
print(sorted_scores_dict)
Output:
{'carol': 78, 'alice': 82, 'bob': 95}
Using operator.itemgetter
A slightly cleaner alternative is itemgetter:
from operator import itemgetter
scores = {
"alice": 82,
"bob": 95,
"carol": 78
}
sorted_scores = sorted(scores.items(), key=itemgetter(1))
print(sorted_scores)
This does the same thing as lambda item: item[1].
When you only need the keys in value order
scores = {
"alice": 82,
"bob": 95,
"carol": 78
}
sorted_names = sorted(scores, key=scores.get)
print(sorted_names)
Output:
['carol', 'alice', 'bob']
This is useful if you only care about the keys, ordered by their values.
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 item[1], which is the value:
- for
('alice', 82), the sort key is82 - for
('bob', 95), the sort key is95 - for
('carol', 78), the sort key is78
Step 4: Python compares the values
It sorts the tuples based on these numbers:
788295
Step 5: Final result
The output becomes:
[('carol', 78), ('alice', 82), ('bob', 95)]
Descending version
If you use:
result = sorted(scores.items(), key=lambda item: item[1], reverse=True)
then Python reverses the order after sorting, giving:
[('bob', 95), ('alice', 82), ('carol', 78)]
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=True)
Useful in text analysis and reporting.
Sorting API response summaries
If you process API data into a dictionary of totals, you may want to sort results before displaying them.
sales_by_region = {
"West": 5400,
"East": 7200,
"North": 6100
}
sorted_regions = sorted(sales_by_region.items(), key=lambda item: item[1], reverse=True)
Useful for dashboards and admin panels.
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=lambda item: item[1]))
Pattern: sorting for output, not storage
In many codebases, the original dictionary is kept unchanged, and sorting is only done when preparing output.
def get_sorted_scores(scores):
return sorted(scores.items(), key=lambda item: item[1], reverse=True)
This avoids accidental side effects.
Pattern: use dict only when order matters in final output
def get_sorted_score_dict(scores):
return dict(sorted(scores.items(), key=lambda item: item[1]))
This can be useful when JSON output or template rendering expects dictionary-style access.
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, item is each key string like "alice", so item[1] means the second character of the string, not the dictionary value.
Correct version:
print(sorted(scores.items(), key=lambda item: item[1]))
Mistake 3: expecting sorted() to return a dictionary
Broken assumption:
scores = {"alice": 82, "bob": 95, "carol": 78}
result = sorted(scores.items(), key=lambda item: item[1])
print(type(result))
This returns a list, not a dict.
If you want a dictionary:
result = dict(sorted(scores.items(), key=lambda item: item[1]))
Mistake 4: trying to sort values that cannot be compared
Broken code:
data = {
"a": 10,
"b": "hello",
"c": 7
}
sorted(data.items(), key=lambda item: item[1])
If values are mixed types, Python may not know how to compare them.
Avoid this by keeping value types consistent.
Mistake 5: assuming the original dictionary changes
scores = {"alice": 82, "bob": 95, "carol": 78}
sorted(scores.items(), key=lambda item: item[1])
print(scores)
The original dictionary stays the same. sorted() creates a new result.
Store the returned value if you need it.
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 | You only need keys ordered by value | sorted(scores, key=scores.get) |
lambda vs itemgetter
| Option | Example | Notes |
|---|---|---|
lambda | key=lambda item: item[1] | Very readable for beginners |
itemgetter | key=itemgetter(1) | Shorter and common in real code |
Ascending vs descending
| Order | Example |
|---|---|
| Ascending | sorted(scores.items(), key=lambda item: item[1]) |
| Descending | sorted(scores.items(), key=lambda item: item[1], reverse=True) |
Dictionary vs list of tuples
- Use a list of tuples if you are displaying ranked results or iterating in sorted order.
- Use a dictionary if you still want key-based lookup after sorting.
- In many cases, the list of tuples is simpler and more explicit.
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
# Lowest to highest
sorted(data.items(), key=lambda item: item[1])
# Highest to lowest
sorted(data.items(), key=lambda item: item[1], reverse=True)
# Top 3 highest values
top_3 = sorted(data.items(), key=lambda item: item[1], reverse=True)[:3]
Edge cases
- Mixed value types may fail during sorting
- Equal values keep their relative order from the original iteration order
- The original dictionary is not modified
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?
Yes:
dict(sorted(my_dict.items(), key=lambda item: item[1]))
What if multiple keys have the same value?
They will appear together in the sorted output. Python keeps a stable sort, so their relative order is preserved.
Is lambda item: item[1] the only way?
No. You can also use:
from operator import itemgetter
sorted(my_dict.items(), key=itemgetter(1))
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.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.