Q&A library Python

How do I build a dictionary with a comprehension in Python?

Python Intermediate comprehensionsdict-comprehensiondictionaries

Short answer

Use braces with a key-value expression and a for clause to build a dictionary in one line. It is clearer than a loop for simple transforms, and a common use is inverting a dictionary or filtering its items.

The short version

A dictionary comprehension builds a dict in one expression, with the shape {key: value for item in iterable}. Add an if to keep only some items. It reads clearly for simple transformations and is the idiomatic way to invert a dictionary, filter its entries, or build a lookup from a pair of sequences.

The basic shape

squares = {n: n * n for n in range(4)}
print(squares)   # {0: 0, 1: 1, 2: 4, 3: 9}

The part before the colon is the key, the part after is the value, and the for clause supplies the items. It mirrors a list comprehension but produces key-value pairs.

Filtering entries

An if at the end keeps only matching items, which is the clean way to make a smaller dictionary from a larger one.

prices = {"pen": 2, "mug": 5, "cup": 4}
dear = {name: p for name, p in prices.items() if p > 3}
print(dear)   # {'mug': 5, 'cup': 4}

Iterating prices.items() gives the key and value together, and the condition drops the cheap ones.

Inverting a dictionary

Swapping keys and values is a classic use, turning a name-to-code map into a code-to-name map.

codes = {"red": "R", "blue": "B"}
inverse = {v: k for k, v in codes.items()}
print(inverse)   # {'R': 'red', 'B': 'blue'}

Note the catch: if two keys shared a value, inverting collapses them, because a dictionary cannot hold duplicate keys and the last one wins. Only invert when the values are unique.

Building from two sequences

Pairing two lists into a dictionary is neatly done with zip inside a comprehension, or directly with dict(zip(...)).

names = ["pen", "mug"]
prices = [2, 5]
{name: price for name, price in zip(names, prices)}   # {'pen': 2, 'mug': 5}

When to prefer a plain loop

As with list comprehensions, keep them simple. If the key or value needs several steps to compute, or you are nesting conditions, a normal loop is easier to read and debug. The comprehension is for concise, single-expression construction, not for cramming complex logic onto one line.

The same brace syntax without a colon builds a set instead, which is handy for collecting the distinct results of a transformation.

{len(word) for word in ["pen", "mug", "cup"]}   # {3}

Enjoying these?

Go from piecing together answers to real fluency.

Our courses take you from looking things up to doing the work with confidence, step by step on real data.

Browse the courses