Python 3 sort a dict by its values
Categories:
Sorting Python Dictionaries by Value: A Comprehensive Guide

Learn various Python 3 techniques to sort dictionaries based on their values, covering both simple and complex scenarios with practical examples.
Dictionaries in Python are inherently unordered collections of key-value pairs. While Python 3.7+ guarantees insertion order for dictionaries, this doesn't mean they are sorted by key or value. Often, you'll encounter situations where you need to process or display dictionary data based on the values associated with each key. This article explores several robust methods to sort a dictionary by its values in Python 3, providing clear explanations and code examples for each approach.
Understanding Dictionary Sorting Limitations
It's crucial to understand that dictionaries themselves cannot be 'sorted' in the traditional sense. When you sort a dictionary, you are actually creating a new ordered collection (like a list of tuples or an OrderedDict
) based on the dictionary's items, sorted by their values. The original dictionary remains unchanged. This distinction is important for maintaining data integrity and understanding the output of sorting operations.
flowchart TD A[Original Dictionary] --> B{Extract Items} B --> C[List of (Key, Value) Tuples] C --> D{Sort List by Value} D --> E[Sorted List of (Key, Value) Tuples] E --> F{Reconstruct Ordered Collection} F --> G[OrderedDict or List of Tuples]
Conceptual flow for sorting a dictionary by its values.
Method 1: Using sorted()
with lambda
for Simple Values
The most common and Pythonic way to sort a dictionary by its values is to use the built-in sorted()
function. This function takes an iterable and returns a new sorted list. To sort by values, we'll extract the dictionary's items (key-value pairs) and provide a key
argument to sorted()
using a lambda
function. The lambda
function will specify that the sorting should be based on the second element of each item tuple (which is the value).
my_dict = {'apple': 3, 'banana': 1, 'cherry': 2, 'date': 4}
# Sort by value in ascending order
sorted_items_asc = sorted(my_dict.items(), key=lambda item: item[1])
print(f"Ascending order: {sorted_items_asc}")
# Sort by value in descending order
sorted_items_desc = sorted(my_dict.items(), key=lambda item: item[1], reverse=True)
print(f"Descending order: {sorted_items_desc}")
# To get a new dictionary (Python 3.7+ preserves insertion order)
sorted_dict_asc = dict(sorted_items_asc)
print(f"Sorted dictionary (asc): {sorted_dict_asc}")
Sorting a dictionary by its values using sorted()
and lambda
.
dict()
constructor on a list of tuples will create a new dictionary where the order is preserved in Python 3.7+. For older versions, you might need collections.OrderedDict
.Method 2: Sorting Dictionaries with Complex Values
When dictionary values are more complex (e.g., lists, other dictionaries, or custom objects), you might need to specify a more intricate sorting key. The lambda
function can be adapted to access specific elements or attributes within these complex values. For instance, if values are lists, you might sort by the first element of the list, or by the length of the list.
complex_dict = {
'item_A': {'price': 100, 'quantity': 5},
'item_B': {'price': 50, 'quantity': 10},
'item_C': {'price': 120, 'quantity': 2}
}
# Sort by 'price' within the nested dictionary value
sorted_by_price = sorted(complex_dict.items(), key=lambda item: item[1]['price'])
print(f"Sorted by price: {sorted_by_price}")
# Sort by 'quantity' in descending order
sorted_by_quantity_desc = sorted(complex_dict.items(), key=lambda item: item[1]['quantity'], reverse=True)
print(f"Sorted by quantity (desc): {sorted_by_quantity_desc}")
Sorting a dictionary by a nested value within its complex values.
'price'
or 'quantity'
) exists for all values to avoid KeyError
exceptions. You might need to add error handling or default values if not all entries are guaranteed to have the same structure.