How to Sort a Dictionary by Value in Python
Introduction
Sorting a dictionary by value in Python is a common task for developers who need to organize data based on its associated values rather than its keys. Learning how to sort a dictionary by value in Python enables you to arrange items, perform ranking, or prepare data for further processing. Now, this guide walks you through the step‑by‑step process, offers multiple code patterns, explains the underlying mechanics, and answers frequent questions. By the end, you will be able to sort any dictionary by its values confidently and efficiently.
Steps to Sort a Dictionary by Value in Python
Using the sorted() Function with a Lambda
The most straightforward approach is to use Python’s built‑in sorted() function together with a lambda expression that extracts the value from each key‑value pair.
my_dict = {'apple': 5, 'banana': 2, 'cherry': 8, 'date': 4}
# Step 1: Convert the dictionary into a list of (key, value) tuples
# Step 2: Sort that list by the second element (the value) using a lambda
sorted_items = sorted(my_dict.items(), key=lambda item: item[1])
# Step 3: Convert the sorted list back into a dictionary (preserves order in Python 3.7+)
sorted_dict = dict(sorted_items)
print(sorted_dict) # Output: {'banana': 2, 'date': 4, 'apple': 5, 'cherry': 8}
Key points
my_dict.items()returns a view of (key, value) tuples.- The
keyparameter ofsorted()tells Python which element to use for comparison;lambda item: item[1]selects the value. - The result of
sorted()is a list, so you must wrap it withdict()to obtain a dictionary that retains the new order.
Using operator.itemgetter
If you prefer a function‑based approach rather than a lambda, the operator module provides itemgetter, which is both concise and slightly faster Simple, but easy to overlook. That alone is useful..
from operator import itemgetter
my_dict = {'apple': 5, 'banana': 2, 'cherry': 8, 'date': 4}
sorted_items = sorted(my_dict.items(), key=itemgetter(1))
sorted_dict = dict(sorted_items)
print(sorted_dict) # {'banana': 2, 'date': 4, 'apple': 5, 'cherry': 8}
Why use itemgetter?
- It avoids the overhead of creating a lambda function.
- It makes the code more readable for developers familiar with the module.
Sorting in Descending Order
Sometimes you need the highest values first. Add the reverse=True argument to sorted() But it adds up..
sorted_desc = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
print(sorted_desc) # {'cherry': 8, 'apple': 5, 'date': 4, 'banana': 2}
In‑Place Sorting (Not Possible Directly)
A dictionary itself cannot be sorted in place because it is a hash table optimized for fast lookups, not ordering. The correct workflow is to create a new dictionary with the sorted items, as shown above. This ensures the original data remains unchanged unless you explicitly assign the result back.
This changes depending on context. Keep that in mind Not complicated — just consistent..
Using Dictionary Comprehension for Concise Code
For those who like compact expressions, a dictionary comprehension can combine the steps:
sorted_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[1])}
This one‑liner reads: “Create a new dictionary where each key‑value pair is taken from the sorted list of items, ordered by the value.”
Explanation of the Process
Understanding how sorting works clarifies why the steps above are necessary And that's really what it comes down to. Turns out it matters..
- Dictionaries are unordered collections (prior to Python 3.7) that store key‑value pairs. Even in newer versions, the insertion order is preserved, but it is not sorted by value.
sorted()works on any iterable, including the list of tuples produced bydict.items(). It returns a new list with elements ordered according to the supplied key function.- The key function (
lambda item: item[1]oritemgetter(1)) extracts the value (the second element) from each tuple, allowing Python to compare values rather than keys. - Conversion back to
dictis required because the sorted result is a list. Since Python 3.7, dictionaries maintain insertion order, so the new dictionary reflects the sorted order.
Italic terms like lambda and itemgetter are highlighted to indicate important Python constructs Simple, but easy to overlook..
Common Pitfalls
- Forgetting to convert back to
dict– leaving the result as a list will cause downstream code that expects a dictionary to fail. - Using the wrong key –
lambda item: item[0]sorts by key, not value; double‑check the index. - Modifying the original dictionary –
sorted()does not altermy_dict; you must assign the result to a new variable. - Assuming order before Python 3.7 – older versions do not guarantee that a dictionary retains sorted order; always rebuild the dict if order matters.
FAQ
Can I sort a dictionary without converting it to a list?
No. Still, dictionaries are not sequences, so sorted() must operate on an iterable such as the list of items returned by dict. items() Easy to understand, harder to ignore. Simple as that..
Does sorting affect the original dictionary?
No. sorted() returns a new list; the original dictionary stays unchanged unless you explicitly assign the sorted dictionary back to the same variable name.
How do I sort by value and then by key for ties?
Provide a tuple in the key function: key=lambda item: (item[1], item[0]). This sorts primarily by value and secondarily by key when values are equal.
What about sorting numeric values versus strings?
Sorting is lexical for strings, meaning '10' comes before '2'. For numeric values, ensure the values are actually numbers (int or float) so that Python orders them numerically rather than alphabetically.
Is there a built‑in method to sort a dictionary?
Python does not provide a direct dict.sort() method. The standard approach is to use sorted() on dict.items() and rebuild the dictionary Simple, but easy to overlook..
Conclusion
Sorting a dictionary by value in Python is a simple yet powerful technique that leverages the built‑in sorted() function and a key extractor—either a lambda or operator.itemgetter. Even so, by converting the dictionary into a list of (key, value) tuples, sorting that list based on the second element, and then converting the result back into a dictionary, you obtain a neatly ordered structure ready for further use. Remember that dictionaries cannot be sorted in place; always create a new dictionary to preserve the sorted order. With the patterns, examples, and troubleshooting tips provided here, you can confidently apply these concepts to real‑world data manipulation tasks. Happy coding!
Beyond the basic pattern, there are several refinements that can make your code both faster and more readable Easy to understand, harder to ignore. But it adds up..
Faster alternatives with operator.itemgetter
If you find yourself repeatedly extracting keys and values, the operator module provides a slightly optimized version:
from operator import itemgetter
# Sort by value, then by key for ties
sorted_items = sorted(my_dict.items(), key=itemgetter(1, 0))
The itemgetter call (itemgetter(1, 0)) creates a callable that fetches the second element first (the value) and, when those are equal, falls back to the first element (the key). This avoids the overhead of constructing a lambda each time while giving you the same two‑level ordering.
Preserving order in pre‑3.7 codebases
Older interpreters do not guarantee insertion order, even though CPython 3.6 already implements a hash‑table that keeps insertion order as an implementation detail. So if you must support versions earlier than 3. 7, consider using *collections.
from collections import OrderedDict
ordered = OrderedDict(sorted(my_dict.items(), key=lambda kv: kv[1]))
The resulting ordered mapping behaves like a regular dictionary in newer Python releases, and it guarantees the desired sequence across all supported runtimes.
Customizing the sort direction
The sorted function accepts a reverse flag. To get descending order simply pass reverse=True:
descending = sorted(my_dict.items(), key=itemgetter(1), reverse=True)
For multi‑level criteria you can chain lambdas or itemgetters; just remember that the tuple comparison works lexicographically, which aligns perfectly with most sorting needs Worth keeping that in mind..
Handling non‑homogeneous values
When some values are numbers and others are strings, mixing types can lead to unexpected results because Python compares different types only under certain conditions. A safe workaround is to normalize everything to strings during the key extraction:
def mixed_key(item):
k, v = item
return (str(v), str(k))
sorted_items = sorted(my_dict.items(), key=mixed_key)
This ensures that the sort never raises a TypeError, albeit at the cost of alphabetical ordering instead of true numerical ordering Most people skip this — try not to. Simple as that..
Performance tip: build the dictionary in one pass
Instead of creating an intermediate list and then rebuilding the dict, you can iterate over the sorted pairs directly:
ordered = {k: v for k, v in sorted(my_dict.items(), key=itemgetter(1))}
Even though this still allocates a temporary list, the comprehension eliminates an explicit loop and makes the intent crystal clear.
Common extensions
- Nested dictionaries: Treat each sub‑dictionary as a single value and sort accordingly.
- Multiple levels: Chain multiple
key=arguments or combine them into a composite itemgetter. - Stability: Because sorted is stable, equal keys retain their original relative order—a handy property when merging datasets.
Conclusion
Sorting a dictionary by its values (or any other attribute) is straightforward once you recognize that dictionaries themselves are unordered mappings and that the sorted routine works on dict.Think about it: itemgetter*—and finally reconstructing a new dictionary, you achieve a clean, ordered structure that integrates smoothly into larger pipelines. Still, by converting the mapping to a list of *(key, value)* pairs, applying a suitable *key* function—whether written as a *lambda* or supplied via *operator. Keep in mind the nuances of type consistency, the difference between pre‑3.Still, following these conventions leads to reliable, performant code that scales well whether you’re processing a handful of entries or millions of rows. In practice, 7 behavior, and the availability of *OrderedDict* for legacy environments. 7 and post‑3.On top of that, items(). Happy coding!
Some disagree here. Fair enough.