programming

Sort dict in Python: a definitive guide to ordering dictionaries

In Python, sorting a dict means producing a new dict with items ordered by key or by value, because the built-in dict type preserves insertion order but does not store items in...

Mara Ellison
Sort dict in Python: a definitive guide to ordering dictionaries

In Python, sorting a dict means producing a new dict with items ordered by key or by value, because the built-in dict type preserves insertion order but does not store items in sorted order automatically. This guide explains how to sort dictionaries in Python using sorted, dict comprehensions, and the standard library, with attention to ordering guarantees introduced in Python 3.7 and practical patterns you can apply today.

How dict ordering works in Python 3.7 and later

From Python 3.7 onward, the built-in dict preserves insertion order as an implementation detail and later guaranteed by the language specification. This means that when you create or update a dict, iterating over it yields items in the order they were added. While this guarantees order, it does not imply that the order is sorted; it only reflects insertion or reassignment sequence. Therefore, to achieve a sorted dict, you must explicitly create a new dict by rearranging items into the desired order, typically by key or by value.

Why you cannot sort a dict in place

Dictionaries are inherently unordered collections in terms of sorting semantics; they do not provide a method that reorders items by key or value in place. To produce a sorted dict, you create a new dict from an iterable of key-value pairs arranged by your chosen criterion. This design keeps dict operations like lookup and insertion fast while giving you full control over sorting logic.

Sort a dict by key in Python

To sort a dictionary by key, use sorted on dict.keys() or directly on the dict, since sorted accepts an iterable of pairs. The most common pattern is to pass the dict items to sorted and then rebuild a dict with a dict comprehension or the dict constructor.

Key-based sorting examples

The simplest approach uses sorted(d.items()), which returns a list of (key, value) pairs sorted by key, then constructs a dict from those pairs. This works for keys that are comparable, such as strings, integers, or tuples of comparable elements.

# Sort by key alphabetically or numerically
sorted_dict = {k: d[k] for k in sorted(d)}

Equivalently, you can write dict(sorted(d.items())) to produce the same ordered dict. For descending order, pass reverse=True to sorted. These patterns are concise, widely used, and compatible with Python 3.6+ where order preservation is consistent.

Sort a dict by value in Python

Sorting by value requires specifying a key function that extracts the value from each item. Use sorted with key=lambda item: item[1] to sort by the second element of each pair, which is the value. As with key sorting, rebuild a dict from the sorted pairs to preserve the order.

Value-based sorting examples

When values are numeric, this approach is straightforward. For more complex ordering, such as descending value or stable ordering of equal values, you can adjust the key function and use operator.itemgetter for clarity and slight performance improvement.

from operator import itemgetter
# Sort by value ascending
sorted_by_value = dict(sorted(d.items(), key=itemgetter(1)))
# Sort by value descending
sorted_by_value_desc = dict(sorted(d.items(), key=itemgetter(1), reverse=True))

Note that when values are equal, the original dict order (insertion order) determines the sequence of items; sorting is stable, so the relative order of equal elements is preserved.

Using the collections.OrderedDict when order matters

When to use OrderedDict vs dict

In Python 3.7+, dict already preserves order, so using collections.OrderedDict is generally unnecessary unless you rely on features it exposes, such as equality tests that ignore order or the move_to_end method. OrderedDict has slightly different semantics and performance characteristics, so prefer dict for typical use cases unless you specifically need those features.

AttributeVerified DetailSource Type
Order guaranteeInsertion order preserved in Python 3.7+ (language guarantee)Language spec
Sorted dict patternUse dict(sorted(d.items(), key=...))Python documentation
PerformanceO(n log n) for sorting, O(n) for building new dictEmpirical measurement
In-place sortNot supported; create new dictAPI reference
Equality semanticsOrderedDict order-sensitive dict equality; dict order ignoredStandard library docs

Common patterns and edge cases

When keys are not directly comparable, ensure they support ordering or provide a key function that returns comparable values. For mixed types, sorting will raise a TypeError unless a custom key normalizes the comparison. With non-string keys, such as integers or tuples, the same dict comprehension and sorted patterns apply.

Practical sorting patterns

  • Sort by key ascending: {k: d[k] for k in sorted(d)}
  • Sort by key descending: {k: d[k] for k in sorted(d, reverse=True)}
  • Sort by value ascending: dict(sorted(d.items(), key=lambda kv: kv[1]))
  • Sort by value descending: dict(sorted(d.items(), key=lambda kv: kv[1], reverse=True))
  • Stable sort with itemgetter: dict(sorted(d.items(), key=itemgetter(1)))

These patterns create a new dict and do not modify the original. If you need to reassign the sorted result, assign it to the same variable to replace the unsorted dict.

Performance considerations and alternatives

Sorting a dictionary involves an O(n log n) comparison sort plus an O(n) pass to build the new dict, which is efficient for most workloads. For very large datasets or repeated sorts, consider whether you can maintain order at insertion time, for example using alternative data structures or keeping a separate sorted list of keys. In typical scripts and services, the dict(sorted(...)) pattern is clear and performant enough.

Compatibility and version-specific notes

Order-preserving dict behavior is guaranteed from Python 3.7 onward. Python 3.6 preserves insertion order as an implementation detail in CPython, but you should not rely on it in code targeting older interpreters. If you need guaranteed order in Python 3.5 or earlier, use OrderedDict. The sorted patterns shown here work across supported versions and remain idiomatic.

Related Reading

More pages in this topic cluster.

How to Sort a List of Strings in Python

Sorting a list of strings in Python is commonly done with sorted(list) or list.sort() . Both accept parameters such as key to customize ordering and reverse to control direction...

Read next
How to Format a Float to 2 Decimal Places in Python

When you format a float to two decimal places in Python, you are controlling how a floating-point number is presented as text, not how it is stored. This article explains the mo...

Read next
How to Round in Python to 2 Decimal Places: Clear, Verified Approaches

To round in Python to 2 decimal places, the most direct options are round(number, 2) , formatted strings like f'{number:.2f}' or '{:.2f}'.format(number) , and the Decimal type w...

Read next