Build a whole dictionary or set in one line: take items from an iterable, optionally filter them, and transform each one.
# basic dict comprehension
squares = {x: x**2 for x in range(5)}
# ans: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# zip two lists
keys = ["a", "b", "c"]
values = [1, 2, 3]
d = {k: v for k, v in zip(keys, values)}
# ans: {'a': 1, 'b': 2, 'c': 3}
# filter dict
numbers = range(10)
even_squares = {x: x**2 for x in numbers
if x % 2 == 0}
# ans: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
# swap dict
original = {"a": 1, "b": 2}
swapped = {v: k for k, v in original.items()}
# ans: {1: 'a', 2: 'b'}
# basic set comprehension
squares = {x**2 for x in range(5)}
# ans: {0, 1, 4, 9, 16}
# auto-removes duplicates
numbers = [1, 2, 2, 3, 3, 3]
unique = {x for x in numbers}
# ans: {1, 2, 3}
# filter set
evens = {x for x in range(10) if x % 2 == 0}
# ans: {0, 2, 4, 6, 8}
Predict the result, then press โ to run the comprehension and check.
# dict comprehension?
{x: x*2 for x in range(3)}
# ans: {0: 0, 1: 2, 2: 4}
# dict from pairs?
pairs = [("a", 1), ("b", 2)]
{k: v for k, v in pairs}
# ans: {'a': 1, 'b': 2}
# dict with if-else?
{x: "even" if x % 2 == 0 else "odd"
for x in range(3)}
# ans: {0: 'even', 1: 'odd', 2: 'even'}
# nested dict?
{i: {j: i*j for j in range(2)}
for i in range(2)}
# ans: {0: {0: 0, 1: 0}, 1: {0: 0, 1: 1}}
The inner comprehension runs once for each i, building that key's value.
# set comprehension duplicates?
{x % 3 for x in range(10)}
# ans: {0, 1, 2} (only unique values)
# set vs list comprehension?
[x for x in [1,2,2,3]]
# ans: [1, 2, 2, 3]
{x for x in [1,2,2,3]}
# ans: {1, 2, 3}
# dict filter values?
d = {"a": 1, "b": 2, "c": 3}
{k: v for k, v in d.items() if v > 1}
# ans: {'b': 2, 'c': 3}
# dict transform values?
d = {"a": 1, "b": 2}
{k: v*2 for k, v in d.items()}
# ans: {'a': 2, 'b': 4}
# set from string?
{c for c in "hello"}
# ans: {'h', 'e', 'l', 'o'}
A set has no order, so Python may print these letters in any order.
# empty dict vs set?
{} # dict
{x for x in []} # set()
Empty braces always mean an empty dict; an empty set prints as set().
{k: v for ...}A colon makes a dict. A repeated key keeps the last value.
{x for ...}No colon makes a set: duplicates disappear, order is not kept.
if at the endFilters which items get in.
a if c else b in frontChooses the value for every item; nothing is filtered out.