Learn Python
>>> data_structures.dict_set_comprehension

Dictionary & Set Comprehension in Python

#concept

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.

#how it works
1

Dictionary comprehension

{key: value for item in iterable} builds key-value pairs directly.

2

Set comprehension

{expr for item in iterable} — the same curly braces as a dict, distinguished by one expression instead of a key:value pair.

3

Both support filtering

An optional if condition at the end works exactly like it does in a list comprehension.

4

Dict comprehensions build lookup tables

Especially useful for pairing up two related lists, or transforming an existing dictionary.

5

Set comprehensions guarantee uniqueness

Useful whenever the result shouldn’t contain duplicates, without a separate call to set() afterward.

#example
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)
Output
{'Ada': 3, 'Grace': 5, 'Alan': 4}
{'A', 'G'}
1{name: len(name) for name in names} loops over each name, using the name itself as the key and its length as the value, building a lookup dictionary.
2{name[0] for name in names} collects the first letter of every name into a set — "Ada" and "Alan" both start with "A", but a set only keeps one copy, giving just two unique letters.
#use cases
Building a fast lookup dictionary from two parallel lists or an existing collection
Inverting a dictionary's keys and values in a single line
Collecting a set of unique values derived from a larger collection, like unique domains from a list of emails
Deduplicating computed results without a separate pass through the data

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.