Python
Dictionary
Sorting
Programming
Data Structures

Sort Dictionary by keys

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Sorting a dictionary by keys is mostly about deterministic output and predictable iteration order. In modern Python, dictionaries preserve insertion order, so rebuilding from sorted items gives stable key traversal. The right technique depends on whether you need one-time display, repeated iteration, or custom key rules.

Basic Key Sorting

The common pattern is sorting dictionary items and rebuilding a dictionary.

python
data = {"b": 2, "a": 1, "c": 3}
sorted_dict = dict(sorted(data.items()))
print(sorted_dict)

Descending order:

python
sorted_desc = dict(sorted(data.items(), reverse=True))
print(sorted_desc)

This is clear and works for most scripts and services.

Iterate in Sorted Order Without Rebuilding

If you only need ordered output once, sort keys during iteration.

python
for key in sorted(data):
    print(key, data[key])

This avoids creating a second dictionary.

Custom Key Sorting Rules

Key sorting often needs business-specific rules, such as case-insensitive ordering.

python
1data = {"Item10": 1, "item2": 2, "Item1": 3}
2
3case_insensitive = dict(
4    sorted(data.items(), key=lambda kv: kv[0].lower())
5)
6print(case_insensitive)

Make key rules explicit so behavior is predictable across environments.

Numeric-Like String Keys

Lexical sorting and numeric sorting differ for strings like "10" and "2".

python
1data = {"10": "x", "2": "y", "1": "z"}
2
3lexical = dict(sorted(data.items()))
4numeric = dict(sorted(data.items(), key=lambda kv: int(kv[0])))
5
6print("lexical", lexical)
7print("numeric", numeric)

Choose the rule that matches domain meaning.

Sorting Nested Dictionaries

For deterministic snapshots of nested objects, sort recursively.

python
1def sort_nested(d: dict) -> dict:
2    out = {}
3    for k, v in sorted(d.items()):
4        out[k] = sort_nested(v) if isinstance(v, dict) else v
5    return out
6
7nested = {"b": {"y": 2, "x": 1}, "a": {"d": 4, "c": 3}}
8print(sort_nested(nested))

This is useful in snapshot tests and config diff generation.

Deterministic JSON Serialization

When exporting data, sorted keys reduce diff noise.

python
1import json
2
3payload = {"z": 1, "a": {"k": 2, "b": 3}}
4print(json.dumps(payload, sort_keys=True))

This is useful for reproducible artifacts and API golden files.

Performance Notes

Sorting keys is O(n log n). For repeated rendering:

  • Sort once and reuse key order.
  • Avoid repeated deep recursive sorting unless necessary.
  • Cache sorted views in high-frequency code paths.

In most applications, correctness and readability matter more than micro-optimizing key sorting.

OrderedDict in Modern Python

Since Python three-seven, built-in dictionaries maintain insertion order by language guarantee. OrderedDict is still valid when its specialized methods are needed, but plain dictionaries are enough in most sorting workflows.

python
from collections import OrderedDict
ordered = OrderedDict(sorted(data.items()))
print(ordered)

Prefer plain dictionary unless you specifically need OrderedDict behavior.

Practical Utility Function

If sorting-by-keys appears repeatedly, centralize behavior in one helper so teams do not reimplement slightly different logic.

python
def sort_dict_by_keys(d: dict, *, reverse: bool = False) -> dict:
    return dict(sorted(d.items(), reverse=reverse))

A shared helper also makes future policy changes easier, for example adding key normalization or validation.

This pattern is especially useful in CLI tools that emit deterministic configuration snapshots for version control and review workflows.

Common Pitfalls

  • Assuming sorted dictionary improves lookup complexity.
  • Mixing incomparable key types and causing runtime sort errors.
  • Using lexical sort where numeric intent is required.
  • Re-sorting keys repeatedly inside hot loops.
  • Forgetting recursive sorting when nested deterministic output is needed.

Summary

  • Use dict(sorted(d.items())) for deterministic key-ordered dictionaries.
  • Sort keys at iteration time when rebuilding is unnecessary.
  • Define explicit key functions for case or numeric-aware ordering.
  • Use recursive sorting for nested deterministic output.
  • Treat key sorting as output and reproducibility control, not lookup optimization.

Course illustration
Course illustration

All Rights Reserved.