Dictionary & Set Comprehension in Python
The same comprehension idea extends beyond lists — a dictionary comprehension builds a new dictionary using {key_expr: value_expr for item in iterable}, and a set comprehension builds a new set using {expr for item in iterable}. Both follow the identical loop-plus-optional-filter pattern as list comprehensions, just with a different bracket style.
Dictionary comprehension
{key: value for item in iterable} builds key-value pairs directly.
Set comprehension
{expr for item in iterable} — the same curly braces as a dict, distinguished by one expression instead of a key:value pair.
Both support filtering
An optional if condition at the end works exactly like it does in a list comprehension.
Dict comprehensions build lookup tables
Especially useful for pairing up two related lists, or transforming an existing dictionary.
Set comprehensions guarantee uniqueness
Useful whenever the result shouldn’t contain duplicates, without a separate call to set() afterward.
names = ["Ada", "Grace", "Alan"] name_lengths = {name: len(name) for name in names}print(name_lengths) first_letters = {name[0] for name in names}print(first_letters)Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.