Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Dict and set comprehensions

Reference for Python dict and set comprehensions: the syntax, filtering with if, nested loops, swapping keys and values, duplicate keys and common mistakes.

A comprehension builds a collection from an iterable in a single expression. A dict comprehension uses braces and a key: value pair; a set comprehension uses braces with a single expression. Both read like the loop they replace: "for each item, produce this entry".

They are the natural tool for transforming data: inverting a mapping, indexing records by an ID, or collecting the unique results of a computation. If the loop body needs several statements, use an ordinary for loop instead.

Python
squares = {n: n * n for n in range(4)}   # {0: 0, 1: 1, 2: 4, 3: 9}
lengths = {len(w) for w in ["a", "bb", "cc"]}   # {1, 2}

Try it

Python Dict 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.

Python Set comprehensions and traps

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.

Forms

Form Example Result
Dict comprehension {k: v for k, v in pairs} A new dict
Set comprehension {x for x in items} A new set
With a filter {x for x in items if x > 0} Only items passing the test
With a conditional value {k: ("big" if v > 9 else "small") for k, v in d.items()} One entry per item
Nested loops {(a, b) for a in A for b in B} Loops nest left to right

The if that filters goes at the end. A conditional expression (x if cond else y) goes in the value part. Mixing the two up is a common syntax error.

Usage notes

  • A new object every time. The source is never modified. Values are not copied, so mutable values are shared with the source.
  • Duplicate keys overwrite. The last matching item wins, but the key keeps the position where it first appeared.
  • Keys and set elements must be hashable. {[1, 2]: 0} and {[1, 2]} raise TypeError.
  • Own scope. The loop variable does not leak into the surrounding code (since Python 3), and it can shadow an outer name only inside the comprehension.
  • Empty set. {} is an empty dict; write set() for an empty set. A set comprehension over nothing still gives a set.
  • Order. Dict results follow the input order. Sets have no meaningful order, so use sorted() when printing.
  • Unpacking is not a comprehension. {**a, **b} merges dictionaries; see merge operators.
  • Readability. Keep it to one loop and at most one condition. Anything longer deserves a named function or a plain loop.