Dict and set comprehensions
Dict and set comprehensions build a new dictionary or set from an iterable using {...} syntax. A dict comprehension writes key: value. A set comprehension writes a single expression.
Detailed Explanation
List comprehensions have two cousins that use braces. {sku: price for sku, price in rows} produces a dictionary. {sku for sku, _ in rows} produces a set. Both are eager. Both accept if filters and extra for clauses. Both use a private scope for the loop names.
The difference is only the expression. A colon makes a dict. No colon makes a set. {} is an empty dict, not an empty set; the empty set is set(). That literal rule is independent of comprehensions and still trips people up when they write empty = {} and then call set methods on it.
Dict comprehensions overwrite on duplicate keys. The last pair for a given key wins, silently. If you are grouping many values per key, a comprehension is the wrong tool; use setdefault, defaultdict, or a loop that appends to a list. If you are inverting a mapping, {value: key for key, value in table.items()} also keeps only the last key for each value.
Set comprehensions drop duplicates because that is what sets do. {name.lower() for name in names} is the usual way to build a case-insensitive membership test. The result is unordered. Do not use a set comprehension when you need first-seen order; use a dict comprehension of {name: True for name in names} (Python 3.7+ preserves insertion) or a loop.
Cost is the same as the equivalent loop plus the hash work of inserting into a dict or set. Unhashable keys (list, dict, other sets) raise TypeError. That is the same rule as table[key] = value.
A generator expression in braces does not exist. {n for n in nums} is a set. (n for n in nums) is a generator. Mixing those brackets is a type change, not a style change.
Prefer a comprehension when the mapping is one expression and an optional filter. Prefer a loop when you need several statements, grouping, or error handling per item.
Code Examples
rows = [("A-1", 950), ("B-2", 400), ("A-1", 999)]
prices = {sku: cents for sku, cents in rows}
print(prices) # {'A-1': 999, 'B-2': 400} <- last A-1 wins
skus = {sku for sku, _ in rows}
print(skus) # {'A-1', 'B-2'}# Filter + transform.
names = ["Ada", "ada", "Linus", ""]
unique = {name.lower() for name in names if name}
print(unique) # {'ada', 'linus'}
index = {name.lower(): name for name in names if name}
print(index["ada"]) # ada <- last spelling for "ada"# Empty braces are a dict. Empty set needs set().
print(type({})) # <class 'dict'>
print(type(set())) # <class 'set'>
print(type({n for n in []})) # <class 'set'>Common Gotchas
Duplicate keys are silent
the last value overwrites earlier ones. If that is not what you want, group in a loop.
Lists are not hashable keys
`{[1]: "a"}` raises `TypeError`. Use a tuple if the key must be a sequence.
`{}` is not an empty set
`unique = {}` then `unique.add("a")` raises `AttributeError`. Write `set()`.
A set comprehension discards order
if you need both uniqueness and order, use a dict or `dict.fromkeys`.