Python Dictionary Comprehensions Explained

Build a dictionary in one line with Python's dict comprehension syntax {k: v for ...}, including filtering and inverting an existing dict.

Published September 17, 2026

A dict comprehension builds a new dictionary from an iterable in a single expression, following the pattern {key_expr: value_expr for item in iterable}.

squares = {x: x * x for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Steps

  1. Write the key and value expressions separated by a colon: x: x * x
  2. Follow with 'for x in range(5)' to define the source values
  3. Optionally add an 'if' clause at the end to filter which pairs are included

How it works

Dict comprehensions work the same way as list comprehensions but produce key-value pairs instead of single values, and are generally faster and more readable than building a dict with a for-loop and repeated assignment.

Things to watch for

  • You can invert an existing dictionary with {v: k for k, v in d.items()}
  • If multiple keys collide, the last one processed wins — comprehensions don't warn about overwritten keys

FAQ

How do I filter a dictionary with a comprehension?

Add an if clause: {k: v for k, v in d.items() if v > 0} keeps only the pairs where the condition is true.

More Python articles