How do I sort a dictionary by value?

Learn how do i sort a dictionary by value? with practical examples, diagrams, and best practices. Covers python, sorting, dictionary development techniques with visual explanations.

How to Sort a Python Dictionary by Value

Hero image for How do I sort a dictionary by value?

Learn various methods to sort a Python dictionary based on its values, including using sorted() with lambda functions and operator.itemgetter.

Dictionaries in Python are inherently unordered collections of key-value pairs (prior to Python 3.7, where insertion order is preserved). While you can't 'sort' a dictionary in place to maintain a specific order, you can obtain a sorted view of its items (key-value pairs) or create a new ordered dictionary based on sorted values. This article explores common and efficient techniques to achieve this, focusing on sorting in both ascending and descending order.

Understanding Dictionary Sorting

When we talk about sorting a dictionary by value, we're typically referring to sorting its items (key-value pairs) based on the values associated with each key. The result is usually a list of tuples, where each tuple contains a key-value pair, or a new OrderedDict (or a regular dictionary in Python 3.7+) constructed from these sorted items. The core of these methods involves using Python's built-in sorted() function, often combined with a key argument to specify the sorting criteria.

flowchart TD
    A[Start] --> B{Dictionary Input}
    B --> C["Extract Items (key, value)"]
    C --> D["Apply sorted() function"]
    D --> E{"Specify Sorting Key"}
    E --> F["Using lambda x: x[1] (value)"]
    E --> G["Using operator.itemgetter(1) (value)"]
    F --> H["Result: List of (key, value) tuples sorted by value"]
    G --> H
    H --> I{Need an OrderedDict?}
    I -->|Yes| J["Create OrderedDict from sorted list"]
    I -->|No| K[End]
    J --> K

Flowchart illustrating the process of sorting a dictionary by value.

Method 1: Using sorted() with a lambda function

The most common and flexible way to sort a dictionary by its values is to use the sorted() built-in function. This function takes an iterable (like dict.items()) and returns a new sorted list. The key argument allows you to specify a function that will be called on each element of the iterable before comparison. For sorting by value, we use a lambda function that extracts the second element (the value) from each key-value tuple.

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}")

Sorting a dictionary by value using sorted() and a lambda function.

Method 2: Using operator.itemgetter

For slightly better performance and readability in some cases, especially when sorting by a specific index of a tuple, you can use operator.itemgetter. This function returns a callable object that fetches the specified item(s) from its operand. When sorting dictionary items (which are tuples of (key, value)), itemgetter(1) will retrieve the value for sorting.

import operator

my_dict = {'apple': 3, 'banana': 1, 'cherry': 2, 'date': 4}

# Sort by value in ascending order using itemgetter
sorted_items_asc = sorted(my_dict.items(), key=operator.itemgetter(1))
print(f"Ascending order (itemgetter): {sorted_items_asc}")

# Sort by value in descending order using itemgetter
sorted_items_desc = sorted(my_dict.items(), key=operator.itemgetter(1), reverse=True)
print(f"Descending order (itemgetter): {sorted_items_desc}")

Sorting a dictionary by value using sorted() and operator.itemgetter.

Creating an Ordered Dictionary from Sorted Items

As mentioned, sorted() returns a list. If your goal is to have a dictionary-like structure that preserves the sorted order, you can pass the sorted list of tuples to the dict() constructor (for Python 3.7+) or collections.OrderedDict (for older Python versions or explicit ordered behavior).

from collections import OrderedDict

my_dict = {'apple': 3, 'banana': 1, 'cherry': 2, 'date': 4}

# Get sorted items
sorted_items = sorted(my_dict.items(), key=lambda item: item[1])

# Create an OrderedDict (works in all Python 3 versions)
ordered_dict = OrderedDict(sorted_items)
print(f"OrderedDict: {ordered_dict}")

# Create a regular dict (Python 3.7+ preserves insertion order)
# For Python < 3.7, this would not guarantee order
regular_ordered_dict = dict(sorted_items)
print(f"Regular dict (Python 3.7+): {regular_ordered_dict}")

Converting sorted items into an OrderedDict or a regular dictionary.