Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 149 ยท Data Structures

Dictionary and Set Comprehensions

Build dictionaries and sets in one readable line with Python comprehensions, filter and transform data, and save memory with lazy generator expressions.

In List Comprehensions you learned to build a list in a single expression: [n * n for n in numbers]. The same idea works for the other collections. Swap the square brackets for curly braces and you get a set comprehension; add a key: value pair and you get a dictionary comprehension. Swap them for parentheses and you get a generator expression, which produces values one at a time instead of building a collection at all.

These forms replace a lot of "create an empty container, loop, add to it" code with one line that says what the result is. This lesson shows each kind, how to filter and transform with them, and when a plain loop is still the better choice.

The shape of a comprehension

All comprehensions share the same parts:

Python
[expression for item in iterable if condition]          # list
{expression for item in iterable if condition}          # set
{key_expr: value_expr for item in iterable if condition}  # dict
(expression for item in iterable if condition)          # generator

Read them left to right as "give me expression for each item in iterable, but only if condition". The if part is optional, and you can chain more than one for for nested loops.

Dictionary comprehensions

A dictionary comprehension builds a dictionary from any iterable. The part before for is a key: value pair:

Python Building dictionaries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When you just pair up two lists without changing anything, dict(zip(products, prices)) is shorter. Comprehensions earn their place when you transform or filter along the way.

Transforming an existing dictionary

Loop over items() to work with both keys and values. This is the standard way to build a modified copy of a dictionary:

Python Transforming dictionaries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The comprehension always creates a new dictionary; the original stays as it was. That's usually what you want, and it also avoids the "dictionary changed size during iteration" error you'd hit if you tried to delete keys while looping.

Warning: Dictionary keys are unique. If the comprehension produces the same key twice, the later value silently replaces the earlier one. Swapping keys and values loses data when two keys share a value.

Conditional values

The if at the end filters items. To choose between two values for every item, put a conditional expression in the value part instead:

Python
scores = {"Ana": 91, "Ben": 58, "Cleo": 74}
result = {name: "pass" if score >= 60 else "fail" for name, score in scores.items()}
# {'Ana': 'pass', 'Ben': 'fail', 'Cleo': 'pass'}

Set comprehensions

A set comprehension uses curly braces with a single expression. Because it builds a set, duplicates disappear automatically:

Python Set comprehensions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Remember that sets have no order, so the examples wrap the results in sorted() to print them neatly.

Note: {} is an empty dictionary, and so is {x: x for x in []}. A set comprehension always has a single expression before for, never a colon.

Nested loops and nested data

You can chain for clauses. They run in the same order as nested loops would, outer first:

Python Nested comprehensions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

sum(name in roster for roster in ...) works because True counts as 1 and False as 0. Notice the long comprehension is split across lines inside the braces; Python lets you break lines freely inside brackets, and it helps readability a lot.

Generator expressions

Write a comprehension with parentheses and you get a generator expression. It doesn't build a list in memory. Instead, it produces each value only when something asks for it. That makes it perfect for feeding functions that consume values one by one, such as sum(), max(), min(), any(), all() and "".join():

Python Generator expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When a generator expression is the only argument to a function, you can drop its own parentheses: sum(n * n for n in numbers) instead of sum((n * n for n in numbers)).

Two things to remember:

  • A generator is lazy: it computes values on demand, so it uses almost no memory even for huge inputs.
  • A generator can be consumed only once. After it's exhausted, it yields nothing. If you need the values twice, build a list.

You'll learn to write your own generator functions with yield in Generators.

When not to use a comprehension

Comprehensions are great for building one collection from another. They're the wrong tool when:

  • The logic is long. If you need several conditions, nested ternaries or three for clauses, a regular loop with clear variable names is easier to read and debug.
  • You want side effects. [print(x) for x in items] builds a useless list of None values. Use a for loop for actions.
  • You'd repeat an expensive call. In {k: slow(k) for k in keys if slow(k) > 0}, slow() runs twice per key. Use a loop, or the walrus operator from Assignment Operators and the Walrus: {k: v for k in keys if (v := slow(k)) > 0}.
Python Comprehension or loop?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first task is a single filter-and-transform step, which is exactly what comprehensions describe well. The second needs a lookup, a default and two updates for every order; squeezing that into one expression would hide the logic.

A good test: if you can read the comprehension aloud as one sentence, keep it. If you have to pause to work out what it does, write the loop.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does {n % 3 for n in range(10)} produce?

    Curly braces with a single expression make a set comprehension, and the set keeps only the unique remainders 0, 1 and 2.
  2. 2. Which comprehension keeps only the entries of prices that cost under 5?

    You loop over items() to get pairs and filter with a trailing if. Option 2 keeps every key but stores True/False as values.
  3. 3. What does type(x * 2 for x in range(3)) report?

    Parentheses around a comprehension make a generator expression, not a tuple. Use tuple(...) if you want a tuple.
  4. 4. g = (n for n in range(3)). What does print(list(g), list(g)) show?

    A generator is consumed once. The first list() takes every value, so the second gets nothing.

Summary

  • A dictionary comprehension {k: v for ...} builds a dictionary; loop over items() to transform or filter an existing one.
  • A set comprehension {x for ...} builds a set and drops duplicates automatically.
  • Add if at the end to filter; use a if cond else b in the expression to choose values.
  • Multiple for clauses run like nested loops, outer first.
  • A generator expression (x for ...) is lazy, memory-friendly and single-use; it's ideal inside sum(), any(), all(), max() and join().
  • Prefer a plain loop when the logic is long or the work has side effects.

Next: Unpacking and Star Expressions, where you'll split sequences into variables and spread values with * and **.