Sponsored Reserved space — layout preview until AdSense is connected

Python

Dictionary comprehensions — build dicts in one readable line

Turn loops that build dictionaries into a single expression, with filters and key/value transforms that stay easy to read.

June 2026 · 6 min read · 4 views · 0 hearts

A dictionary comprehension builds a dict from an iterable in one expression, the same way a list comprehension builds a list. The shape is {key: value for item in iterable}, and you can add an if clause to keep only the entries you want.

The basic form

Say you have a list of words and want their lengths:

words = ["async", "def", "yield"]
lengths = {w: len(w) for w in words}
# {'async': 5, 'def': 3, 'yield': 5}

Filtering and transforming

Add a condition to drop entries, and transform the key or value inline. This reads top-to-bottom like a sentence, which is the whole point:

prices = {"pen": 1.5, "book": 12.0, "pin": 0.2}
affordable = {k.title(): round(v) for k, v in prices.items() if v < 10}
# {'Pen': 2, 'Pin': 0}

When to reach for a loop instead

If the logic needs several statements, try/except, or you are building more than one structure at once, a plain for loop is clearer. Comprehensions shine for a single, side-effect-free mapping — not for everything.

Comments

Questions, corrections, and tips stay visible for everyone reading this page.

0 in thread

Join the discussion

Shown next to your comment.

Constructive tone · up to 4,000 characters

No comments yet

Be the first to leave a note — it helps the next reader.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected