Python › Comprehensions & Generators

How do dict comprehensions and set comprehensions differ in syntax from list comprehensions?

Intermediate

Answer

A dict comprehension uses curly braces with a 'key: value' pair (`{k: v for ...}`), producing a dictionary; a set comprehension uses curly braces with just an expression (`{expr for ...}`, no colon), producing a set with automatically deduplicated values — both otherwise support the same for/if clauses as list comprehensions.
squares_dict = {n: n * n for n in range(5)}
print(squares_dict)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

unique_lengths = {len(word) for word in ["cat", "dog", "bird", "ox"]}
print(unique_lengths)  # {3, 4, 2}
Real-world example Building a lookup dictionary from a list of objects (keyed by ID), or a set of unique values derived from a list.

Common follow-ups: How would you write a comprehension that produces a dict from two PARALLEL lists using zip()?