How to Sort a Dictionary by Value in Python

Learn how to sort a Python dictionary by its values. Discover sorting using sorted(), custom key lambdas, and building ordered dict structures.

Try Code in Editor

Explanation

While dictionaries are primarily built for quick lookup operations using unique keys, you will often need to sort dictionary items based on their values. For example, sorting students by their exam marks, listing products from cheapest to most expensive, or ordering word counts by frequency.

In Python, you cannot directly sort a dictionary in-place because standard dictionary structures do not support ordering methods like lists. Instead, the standard approach is to retrieve the dictionary's items as tuples using the `.items()` method, sort those tuples using the built-in `sorted()` function with a custom sorting key, and then rebuild the dictionary from the sorted items.

The sorting key is typically a lambda function that returns the second element of the tuple (the dictionary value): `key=lambda item: item[1]`. Since Python 3.7+, standard dictionaries preserve insertion order. Re-casting the sorted list of tuples back into a dictionary using the `dict()` constructor returns a clean, sorted dictionary ready for iteration.

Step-by-Step Implementation

  1. 1

    Call my_dict.items() to retrieve key-value pairs as a list of tuples.

  2. 2

    Pass the dictionary items to the sorted() function.

  3. 3

    Specify key=lambda item: item[1] to instruct the sorted() function to sort based on the value (second element of each tuple).

  4. 4

    Pass reverse=True as an optional argument to sort the items in descending order.

  5. 5

    Rebuild the sorted dictionary by passing the sorted list of tuples to the dict() constructor.

Code Example

This script demonstrates sorting a dictionary of test scores by values in both ascending and descending order using lambda functions.

sort_dict_values.py
Try in Editor
scores = {"Alice": 88, "Bob": 75, "Charlie": 95, "David": 82}
print("Original dictionary:", scores)

# 1. Sort by values (ascending order)
sorted_ascending = dict(sorted(scores.items(), key=lambda item: item[1]))
print("Sorted ascending:", sorted_ascending)

# 2. Sort by values (descending order)
sorted_descending = dict(sorted(scores.items(), key=lambda item: item[1], reverse=True))
print("Sorted descending:", sorted_descending)

# 3. sorting by keys for comparison
sorted_keys = dict(sorted(scores.items(), key=lambda item: item[0]))
print("Sorted by keys:", sorted_keys)
Terminal Output
Original dictionary: {'Alice': 88, 'Bob': 75, 'Charlie': 95, 'David': 82}
Sorted ascending: {'Bob': 75, 'David': 82, 'Alice': 88, 'Charlie': 95}
Sorted descending: {'Charlie': 95, 'Alice': 88, 'David': 82, 'Bob': 75}
Sorted by keys: {'Alice': 88, 'Bob': 75, 'Charlie': 95, 'David': 82}

Frequently Asked Questions

What does key=lambda item: item[1] mean?

The sorted() function passes each element of the items sequence (a tuple of (key, value)) to the lambda function. item[1] extracts the value component, telling Python to sort the tuples by value.

Does sorting a dictionary affect its key lookup speed?

No, key lookups remain O(1) average time complexity because sorting only changes the iteration sequence, not the underlying hash table structure.

Related How-To Guides

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.