Python Sorting A Dictionary By Value

5 min read

Sorting a dictionary by value is one of the most common tasks Python developers encounter, whether they are cleaning data, building leaderboards, or preparing reports for visualization. Unlike lists, dictionaries in Python are inherently unordered collections of key-value pairs (though insertion order is preserved as of Python 3.Still, 7). This means you cannot "sort" a dictionary in place the way you would a list. Instead, the standard workflow involves extracting the items, sorting them based on the value, and reconstructing a new dictionary or a list of tuples. Mastering the sorted() function alongside lambda expressions or the operator module unlocks a clean, Pythonic way to handle this requirement efficiently.

This is the bit that actually matters in practice.

Understanding the Core Mechanism: The sorted() Function

The built-in sorted() function is the workhorse for this operation. When applied to a dictionary, iterating over the dictionary directly yields keys. And it accepts any iterable and returns a new list containing the elements in ascending order by default. To sort by values, you must explicitly tell Python to look at the second element of each key-value pair Not complicated — just consistent..

The syntax relies heavily on the key parameter. Practically speaking, this parameter accepts a function that is called on each element before comparison. For dictionaries, the most readable approach uses a lambda function.

Consider a dictionary representing student grades:

grades = {'Alice': 88, 'Bob': 75, 'Charlie': 92, 'David': 85}

To sort this by the grade (the value), you pass grades.items() to sorted(). The .items() method returns a view object yielding (key, value) tuples. The lambda function lambda item: item[1] instructs the sorter to use the second element of the tuple (the value) as the sorting criterion Small thing, real impact..

sorted_grades = sorted(grades.items(), key=lambda item: item[1])
# Result: [('Bob', 75), ('David', 85), ('Alice', 88), ('Charlie', 92)]

Notice the output is a list of tuples, not a dictionary. Now, since Python 3. Because of that, this is a crucial distinction. If you need a dictionary back, you must pass this list into the dict() constructor. 7 guarantees insertion order preservation, the resulting dictionary will maintain the sorted order Less friction, more output..

No fluff here — just what actually works.

sorted_dict = dict(sorted(grades.items(), key=lambda item: item[1]))
# Result: {'Bob': 75, 'David': 85, 'Alice': 88, 'Charlie': 92}

Sorting in Descending Order

Real-world scenarios often demand the highest values first—top scores, most expensive items, or highest frequency counts. The sorted() function handles this natively via the reverse parameter. Setting reverse=True flips the sort order without requiring complex logic or negative value manipulation Worth keeping that in mind..

top_performers = dict(sorted(grades.items(), key=lambda item: item[1], reverse=True))
# Result: {'Charlie': 92, 'Alice': 88, 'David': 85, 'Bob': 75}

This single boolean flag is significantly more readable and performant than multiplying values by -1 or writing custom comparison logic, keeping your code declarative and intent clear That alone is useful..

Leveraging the operator Module for Performance

While lambda functions are perfectly adequate for most scripts, the operator module provides a faster, more optimized alternative: itemgetter. This is particularly relevant when sorting massive datasets containing millions of records, where the overhead of a Python function call (lambda) for every single comparison adds up.

operator.itemgetter(1) creates a callable that fetches the second index of a sequence. It is implemented in C, making it measurably faster than a lambda equivalent Still holds up..

from operator import itemgetter

# Using itemgetter(1) to grab the value (index 1 of the tuple)
sorted_grades_fast = dict(sorted(grades.items(), key=itemgetter(1)))

In benchmarks, itemgetter typically outperforms lambda by 10-20%. For a script running once, the difference is negligible. For a high-throughput data pipeline, it is a worthwhile optimization that requires minimal code change Less friction, more output..

Handling Complex Values: Nested Structures and Objects

Dictionaries in production code rarely map keys to simple integers or strings. Values are often lists, tuples, custom objects, or nested dictionaries. The key parameter shines here because you can write arbitrary logic to extract the specific attribute you want to sort by.

Quick note before moving on.

Sorting by a Specific Index in a List Value

Imagine a dictionary tracking product inventory where the value is a list [stock_quantity, price]. You want to sort by price (index 1 of the list).

inventory = {
    'Widget A': [50, 10.99],
    'Widget B': [200, 5.50],
    'Widget C': [10, 25.00]
}

# Sort by price (index 1 of the value list)
sorted_by_price = dict(sorted(inventory.items(), key=lambda item: item[1][1]))
# Result: {'Widget B': [200, 5.5], 'Widget A': [50, 10.99], 'Widget C': [10, 25.0]}

Sorting by an Attribute of a Custom Object

If your values are instances of a class, you access attributes using dot notation inside the lambda It's one of those things that adds up..

from dataclasses import dataclass

@dataclass
class Employee:
    name: str
    department: str
    salary: int

staff = {
    101: Employee('John', 'Engineering', 90000),
    102: Employee('Jane', 'Marketing', 75000),
    103: Employee('Doe', 'Engineering', 95000)
}

# Sort by salary attribute
sorted_staff = dict(sorted(staff.items(), key=lambda item: item[1].salary))

This flexibility makes the sorted() + key pattern the universal solution for ordering mappings in Python, regardless of data complexity.

Sorting by Key as a Tie-Breaker

What happens when two items have the exact same value? Even so, relying on insertion order for tie-breaking can be brittle. Python’s sort is stable, meaning it preserves the original order of equal elements. A strong approach defines a secondary sort key explicitly.

You can return a tuple from the key function. Python compares tuples element by element: it sorts by the first element, then the second, and so on.

scores = {'Player1': 100, 'Player2': 90, 'Player3': 100, 'Player4': 80}

# Sort by score (descending), then by name (ascending) for ties
# We negate the score for descending sort on the first tuple element
# Or use reverse=True carefully. 
# Better approach for mixed directions: sort twice (stable sort) or use tuple with negative.
leaderboard = dict(sorted(scores.items(), key=lambda item: (-item[1], item[0])))
# Result: {'Player1': 100, 'Player3': 100, 'Player2': 90, 'Player4': 80}

Here, -item[1] sorts scores descending (high to low), and item[0] sorts player names ascending (alphabetical) for the tied 100s. This technique is essential for deterministic leaderboards and consistent reporting.

Common Pitfalls and Best Practices

1. Attempting In-Place Sorting

Dictionaries do not have a .sort() method. Writing `

Just Hit the Blog

New Content Alert

Branching Out from Here

More to Discover

Thank you for reading about Python Sorting A Dictionary By Value. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home