← Back to Core Python
Lesson 22 · Python Collections

Dictionary and Set Comprehensions

Build dictionaries and sets in one expression - lookups, filtered copies, inverted maps, unique values - and know when a loop is still the right tool.

Beginner40 min

What you will be able to do

  • Build a dictionary with {key: value for item in iterable}
  • Build dictionaries from two lists, from enumerate(), and from a list of records keyed by id
  • Filter and transform an existing dictionary through .items()
  • Invert a dictionary - and explain what happens when two keys share a value
  • Build a set with {expression for item in iterable}, and tell it apart from a dict by the colon
  • Explain why there is no tuple comprehension, and what (x for x in items) really is
  • Recognise when dict(zip()), dict.fromkeys() or a plain loop is the better choice

The idea, in plain English

Lesson 21 built lists in one expression. The same idea works for the two other collections you build all the time: dictionaries and sets. Swap the square brackets for curly braces.

Put key: value at the front and you get a dictionary: {name: len(name) for name in names}. Put a single expression at the front - no colon - and you get a set: {city.title() for city in cities}. The colon is the only difference, and it decides which one you build. Filtering with if at the end and choosing with if/else at the front work exactly as in Lesson 21.

Dictionary comprehensions shine at reshaping data: a lookup by id, a filtered copy, an inverted map. Set comprehensions collect unique values. Neither is right for counting or grouping - those need to look at what was built so far, which is a loop’s job (Lesson 20). Every output below comes from running the code in Python 3.14.

Worked example: Inverting a dictionary's keys and values.

An everyday example: the class register

A teacher has the class register - a list of students, each with a roll number, a name and a home city. From it she makes three things:

  • A lookup card: roll number -> name, so she can find a student fast. That is a dictionary comprehension: {s["roll"]: s["name"] for s in students}.
  • A reverse card: name -> roll number. That is the dictionary turned around - an inverted dict.
  • But two students are both called Ravi. On the reverse card, the second Ravi’s number replaces the first. An inverted dict keeps only one key per value.
  • A list of the cities students come from, each written once. That is a set comprehension: {s["city"] for s in students}.
  • One thing she does NOT do in one line: count how many students per city. For that she goes down the register with a tally - a loop.
The story -> the comprehension
Roll number -> name cardA dict comprehension: key: value at the front.
Name -> roll number cardInverting: swap key and value.
Two students called RaviRepeated values: the last one wins.
Cities, each written onceA set comprehension: no colon.
Counting students per cityNot a comprehension - a loop with get().

The dictionary comprehension

It is the loop that fills an empty dictionary, in one expression:

  • The empty dict and the result[key] = value line disappear - the curly braces do that job.
  • The key: value pair moves to the FRONT: name: len(name).
  • The for clause follows: for name in names.
  • Read it as: "name maps to len(name), for each name in names".
  • Keys must be unique, as always. If the same key comes up twice, the later value replaces the earlier one.
A loop, then the same dictionary as a comprehension
names = ["Ravi", "Kiran", "John"] # The loop lengths = {} for name in names: lengths[name] = len(name) print(lengths) # {'Ravi': 4, 'Kiran': 5, 'John': 4} # The same dictionary, as a comprehension lengths = {name: len(name) for name in names} print(lengths) # {'Ravi': 4, 'Kiran': 5, 'John': 4} print({n: n * n for n in range(1, 6)}) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} print({word: word.upper() for word in ["py", "js"]}) # {'py': 'PY', 'js': 'JS'}
Same dictionary, two ways
lengths = {}Gone - the { } creates the dictionary.
for name in names:Becomes the for clause: for name in names
lengths[name] = len(name)The pair moves to the front: name: len(name)
Resultlengths = {name: len(name) for name in names}

Building a dictionary from other data

  • Two lists side by side: zip() them - {name: age for name, age in zip(names, ages)}. When you just pair them as they are, dict(zip(names, ages)) is simpler.
  • Positions as keys: enumerate() - {i: name for i, name in enumerate(names, start=101)}.
  • A list of records keyed by id: {u["id"]: u for u in users}. This is Lesson 20’s lookup table in one line - and one of the most common lines in backend code.
  • Just one field per record: {u["id"]: u["name"] for u in users}.
  • Text: "name=Ravi;city=Pune" -> split it, then split each piece.
zip, enumerate, records by id, text
names = ["Ravi", "Kiran", "John"] ages = [30, 28, 35] print({name: age for name, age in zip(names, ages)}) # {'Ravi': 30, 'Kiran': 28, 'John': 35} print(dict(zip(names, ages))) # the same - simpler when you just pair them print({i: name for i, name in enumerate(names, start=101)}) # {101: 'Ravi', 102: 'Kiran', 103: 'John'} users = [ {"id": 101, "name": "Ravi", "city": "Pune"}, {"id": 102, "name": "Kiran", "city": "Delhi"}, {"id": 103, "name": "John", "city": "Pune"}, ] by_id = {u["id"]: u for u in users} print(by_id[102]) # {'id': 102, 'name': 'Kiran', 'city': 'Delhi'} print({u["id"]: u["name"] for u in users}) # {101: 'Ravi', 102: 'Kiran', 103: 'John'} line = "name=Ravi;city=Pune;role=admin" print({pair.split("=")[0]: pair.split("=")[1] for pair in line.split(";")}) # {'name': 'Ravi', 'city': 'Pune', 'role': 'admin'}

Filtering and changing an existing dictionary

Loop over d.items() to get each key and value, then build a new dictionary from them:

  • Keep only some entries: if at the end - {k: v for k, v in prices.items() if v >= 100}.
  • Change every value: put a new expression after the colon.
  • Change every key: put a new expression before the colon.
  • Choose a value: if/else at the front, after the colon - exactly as in Lesson 21.
  • Drop some keys: if k not in private - a set of keys to remove.
  • The original dictionary is never changed. You always get a new one.
Filter, transform, choose, remove
prices = {"pen": 20, "book": 250, "bag": 900, "ink": 60} # Keep only some entries print({item: price for item, price in prices.items() if price >= 100}) # {'book': 250, 'bag': 900} # Change every value print({item: round(price * 1.18, 2) for item, price in prices.items()}) # {'pen': 23.6, 'book': 295.0, 'bag': 1062.0, 'ink': 70.8} # Change every key print({item.upper(): price for item, price in prices.items()}) # {'PEN': 20, 'BOOK': 250, 'BAG': 900, 'INK': 60} # Both: filter and change print({item: price - 10 for item, price in prices.items() if price < 100}) # {'pen': 10, 'ink': 50} # Choose a value with if/else at the front print({item: "expensive" if price > 200 else "cheap" for item, price in prices.items()}) # {'pen': 'cheap', 'book': 'expensive', 'bag': 'expensive', 'ink': 'cheap'} # Remove some keys - e.g. before sending a user record to a browser private = {"password", "token"} user = {"name": "Ravi", "password": "x1", "token": "abc", "city": "Pune"} print({k: v for k, v in user.items() if k not in private}) # {'name': 'Ravi', 'city': 'Pune'}

Inverting a dictionary

  • A dictionary only looks up one way: codes["IN"] gives "India", but nothing gives "IN" from "India".
  • Swap each pair: {country: code for code, country in codes.items()}.
  • This is safe ONLY when the values are unique.
  • When two keys share a value, they both become the same key in the inverted dict - and the LAST one wins. Three entries in, two out, no error.
  • If values can repeat, you need a dictionary of lists instead. Each key COLLECTS several values, so it depends on what was built so far - that is a loop with setdefault() (Lesson 20).
Inverting - and losing an entry
codes = {"IN": "India", "US": "United States", "JP": "Japan"} inverted = {country: code for code, country in codes.items()} print(inverted) # {'India': 'IN', 'United States': 'US', 'Japan': 'JP'} print(inverted["Japan"]) # JP # When values repeat, the LAST key wins course_of = {"Ravi": "Python", "Kiran": "Java", "John": "Python"} print({course: name for name, course in course_of.items()}) # {'Python': 'John', 'Java': 'Kiran'} - Ravi is gone print(len(course_of), "->", len({course: name for name, course in course_of.items()})) # 3 -> 2 # Group instead - a loop, because each key collects several values students_by_course = {} for name, course in course_of.items(): students_by_course.setdefault(course, []).append(name) print(students_by_course) # {'Python': ['Ravi', 'John'], 'Java': ['Kiran']}

Watch out: An inverted dictionary silently drops entries whenever two keys share a value. If you are not sure the values are unique, compare len() before and after.

Set comprehensions

  • Curly braces with a single expression - no colon - build a set: {c.title() for c in cities}.
  • A set keeps each value once, so a set comprehension removes duplicates as it builds (Lesson 18).
  • Clean the values first, or near-duplicates survive: "Pune" and "pune" are different strings.
  • A set has no order, and sets of strings print in a different order on different runs. Use sorted() when you show one.
  • Watch the empty case: {} is an empty DICTIONARY. An empty set is set().
Unique values in one line
cities = ["Pune", "Delhi", "pune", "Mumbai", "Delhi"] print({c for c in cities}) # {'pune', 'Pune', 'Delhi', 'Mumbai'} - order may vary print({c.title() for c in cities}) # {'Mumbai', 'Pune', 'Delhi'} - order may vary print(sorted({c.title() for c in cities})) # ['Delhi', 'Mumbai', 'Pune'] emails = ["ravi@gmail.com", "kiran@yahoo.com", "john@gmail.com"] print({e.split("@")[1] for e in emails}) # {'yahoo.com', 'gmail.com'} - order may vary print({n % 3 for n in range(10)}) # {0, 1, 2} # The colon decides - and {} on its own is a dict print(type({}), type(set()), type({1})) # <class 'dict'> <class 'set'> <class 'set'> print(type({x: 1 for x in "ab"}), type({x for x in "ab"})) # <class 'dict'> <class 'set'>

There is no tuple comprehension

  • Round brackets look like they should make a tuple. They do not.
  • (n * n for n in range(4)) is a generator expression - it hands out values one at a time, and only once (Lesson 48).
  • To get a tuple, pass it to tuple(): tuple(n * n for n in range(4)).
  • A generator is used up after one pass: a second tuple() of the same generator is empty.
Round brackets make a generator
g = (n * n for n in range(4)) print(type(g).__name__) # generator - not a tuple print(tuple(n * n for n in range(4))) # (0, 1, 4, 9) print(tuple(g)) # (0, 1, 4, 9) print(tuple(g)) # () - already used up

When a loop or a built-in is better

  • COUNTING: {w: words.count(w) for w in words} looks neat, but count() walks the whole list for every word. On 5,000 words it was about 900 times slower than Lesson 20’s one-pass loop on our machine.
  • GROUPING: each key collects several values, so it depends on what was built so far. Use a loop with setdefault().
  • Pairing two lists as they are: dict(zip(keys, values)) says it more simply.
  • The same starting value for every key: dict.fromkeys(keys, 0) - fine for numbers and strings. (For a list as the value, use a comprehension, so each key gets its own list.)
  • And as in Lesson 21: if it does not fit on one easy line, write the loop.
Counting: the neat line that is slow
words = "the cat and the dog and the bird".split() # Looks neat - but list.count() walks the whole list for every word print({w: words.count(w) for w in words}) # {'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1} # One pass instead (Lesson 20) count = {} for w in words: count[w] = count.get(w, 0) + 1 print(count) # {'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1} # Timed on 5,000 words (500 different ones), our machine: # comprehension with count(): 1.345 s # one-pass loop: 0.0015 s # about 903 times slower # The same start value for every key print(dict.fromkeys(["a", "b", "c"], 0)) # {'a': 0, 'b': 0, 'c': 0} print({k: 0 for k in ["a", "b", "c"]}) # {'a': 0, 'b': 0, 'c': 0}

The worked example: a product catalogue

A list of products, the way an API returns them. Each question is one comprehension:

  • Price by SKU, for fast lookups - a dict keyed by id.
  • Name and price of the items worth 100 or more - a filtered dict.
  • Every tag used anywhere - a set comprehension with two for clauses (each product has a list of tags).
  • Which products have each tag - a dict whose values are list comprehensions.
  • Line totals for a cart - a dict built from the cart, using the price lookup.
Five questions about a catalogue
products = [ {"sku": "P1", "name": "Pen", "price": 20, "tags": ["office", "cheap"]}, {"sku": "P2", "name": "Bag", "price": 900, "tags": ["travel"]}, {"sku": "P3", "name": "Ink", "price": 60, "tags": ["office"]}, {"sku": "P4", "name": "Lamp", "price": 1500, "tags": ["home", "office"]}, ] price_of = {p["sku"]: p["price"] for p in products} print(price_of) # {'P1': 20, 'P2': 900, 'P3': 60, 'P4': 1500} print({p["name"]: p["price"] for p in products if p["price"] >= 100}) # {'Bag': 900, 'Lamp': 1500} all_tags = {tag for p in products for tag in p["tags"]} print(sorted(all_tags)) # ['cheap', 'home', 'office', 'travel'] print({tag: [p["name"] for p in products if tag in p["tags"]] for tag in sorted(all_tags)}) # {'cheap': ['Pen'], 'home': ['Lamp'], 'office': ['Pen', 'Ink', 'Lamp'], 'travel': ['Bag']} cart = {"P1": 3, "P3": 2, "P4": 1} line_totals = {sku: qty * price_of[sku] for sku, qty in cart.items()} print(line_totals, sum(line_totals.values())) # {'P1': 60, 'P3': 120, 'P4': 1500} 1680

The forms

The colon decides: key: value builds a dict, a single expression builds a set.

Dict

A key and a value for every item.

{name: len(name) for name in names}
Dict from records

A lookup by id.

{u["id"]: u for u in users}
Filter a dict

Keep only some entries.

{k: v for k, v in d.items() if v > 0}
Change values

Same keys, new values.

{k: v * 2 for k, v in d.items()}
Invert

Values become keys - unique values only.

{v: k for k, v in d.items()}
Set

Unique values, no order.

{c.title() for c in cities}

Built-ins that do the same job more simply

dict(zip(keys, values))

Pair two lists as they are.

dict(zip(names, ages))
dict.fromkeys(keys, value)

The same value for every key - numbers and strings only.

dict.fromkeys(names, 0)
set(iterable)

Unique values, without changing them.

set(cities)
tuple(gen)

A tuple from a generator expression.

tuple(n * n for n in nums)
sorted(a_set)

A set’s values as a list, in order.

sorted({c.title() for c in cities})

Try it yourself

The code does not change. Swap the content string and the program does something else entirely.

Loop to one line

“Take the users_by_id loop from Lesson 20 and rewrite it as a dict comprehension. Check both give the same dictionary.”

Lose an entry

“Invert {"Ravi": "Python", "Kiran": "Java", "John": "Python"} and compare len() before and after. Which name disappeared, and why that one?”

Remove the colon

“Run {c: 1 for c in "hello"}, then {c for c in "hello"}. What type is each, and why does "l" appear once?”

The empty braces

“Print type({}) and type(set()). Then try {}.add(1) and read the error.”

Use a generator twice

“g = (n for n in range(3)); print(list(g)); print(list(g)). Why is the second list empty?”

What usually goes wrong

Forgetting the colon - and getting a set

Without key: value, the braces build a set, not a dictionary. Python does not warn you; the error comes later, when you try to look something up.

✗ {name, len(name) for name in names}   # SyntaxError
{name for name in names}              # a set
✓ {name: len(name) for name in names}
Inverting when values repeat

Repeated values collapse into one key, and the last one wins - no error. Group into lists with a loop instead.

✗ {course: name for name, course in course_of.items()}
✓ groups.setdefault(course, []).append(name)   # in a loop
Counting with list.count() inside a comprehension

count() walks the whole list for every item - about 900 times slower than one pass, on 5,000 words.

✗ {w: words.count(w) for w in words}
✓ for w in words:
    count[w] = count.get(w, 0) + 1
Writing {} for an empty set

{} is an empty dictionary. Calling .add() on it raises AttributeError.

✗ seen = {}
✓ seen = set()
Expecting round brackets to make a tuple

(x for x in items) is a generator, used up after one pass. Wrap it in tuple() if you want a tuple.

✗ squares = (n * n for n in nums)   # a generator
✓ squares = tuple(n * n for n in nums)
Iterating a dict without .items()

Looping over a dictionary gives only its keys. To get the key AND the value, loop over .items().

✗ {k: v for k, v in prices}
✓ {k: v for k, v in prices.items()}

Best practices

  • Use a dict comprehension to reshape data: a lookup by id, a filtered copy, changed values.
  • Loop over d.items() whenever you need both the key and the value.
  • Only invert a dictionary when you know the values are unique.
  • Use a loop for counting and grouping - they depend on what has been built so far.
  • Prefer dict(zip(a, b)) and set(items) when you are not changing anything.
  • Sort a set before you show it; its order is not stable between runs.
  • Write set() for an empty set, never {}.

Practice

Write these yourself before opening anything. Getting them wrong first is most of how this sticks.

1.

Build a dictionary mapping each number from 1 to 5 to its cube.

Show hint

n: n ** 3 at the front.

Show solution
print({n: n ** 3 for n in range(1, 6)}) # {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
2.

From ["sun", "python", "ai", "data", "code"], map each word longer than 3 letters to its length.

Show hint

A filter at the end: if len(w) > 3.

Show solution
words = ["sun", "python", "ai", "data", "code"] print({w: len(w) for w in words if len(w) > 3}) # {'python': 6, 'data': 4, 'code': 4}
3.

Invert {"a": 1, "b": 2, "c": 3}.

Show hint

Loop over .items() and swap the order in the pair.

Show solution
letters = {"a": 1, "b": 2, "c": 3} print({v: k for k, v in letters.items()}) # {1: 'a', 2: 'b', 3: 'c'}
4.

From ["Ravi", "rahul", "Kiran", "anil", "Arjun"], build the set of first letters, in lowercase. Print it sorted.

Show hint

n[0].lower(), with no colon.

Show solution
names = ["Ravi", "rahul", "Kiran", "anil", "Arjun"] print(sorted({n[0].lower() for n in names})) # ['a', 'k', 'r']
5.

Remove every entry whose value is None from {"name": "Ravi", "phone": None, "city": "Pune", "email": None}.

Show hint

Filter with is not None - not truthiness, so a 0 or "" would stay (Lesson 9).

Show solution
profile = {"name": "Ravi", "phone": None, "city": "Pune", "email": None} print({k: v for k, v in profile.items() if v is not None}) # {'name': 'Ravi', 'city': 'Pune'}
6.

Given {"pen": 20, "bag": 900, "lamp": 1500, "ink": 60}, take 10% off every price above 500 and leave the rest unchanged.

Show hint

Every item stays, so the if/else goes at the front, after the colon.

Show solution
prices = {"pen": 20, "bag": 900, "lamp": 1500, "ink": 60} print({k: v * 0.9 if v > 500 else v for k, v in prices.items()}) # {'pen': 20, 'bag': 810.0, 'lamp': 1350.0, 'ink': 60}
Coding challenge

A marks report from flat records

Each record is one student’s mark in one subject - the shape a database table returns. Answer each question with a dictionary or set comprehension.

It should
  • The set of all students, and the set of all subjects - print them sorted.
  • A dictionary of Python marks: student -> mark, for Python records only.
  • A dictionary of total marks per student.
  • A dictionary of "pass" or "fail" per student - a total of 150 or more passes.
  • The students who took Python but not SQL, using two set comprehensions and set difference (Lesson 18).
records = [ {"name": "Ravi", "subject": "Python", "marks": 78}, {"name": "Ravi", "subject": "SQL", "marks": 85}, {"name": "Kiran", "subject": "Python", "marks": 45}, {"name": "Kiran", "subject": "SQL", "marks": 62}, {"name": "John", "subject": "Python", "marks": 91}, {"name": "John", "subject": "Java", "marks": 70}, ] # 1. All students, all subjects # 2. Python marks by student # 3. Total marks per student # 4. Pass or fail per student # 5. Took Python but not SQL
Show one solution
records = [ {"name": "Ravi", "subject": "Python", "marks": 78}, {"name": "Ravi", "subject": "SQL", "marks": 85}, {"name": "Kiran", "subject": "Python", "marks": 45}, {"name": "Kiran", "subject": "SQL", "marks": 62}, {"name": "John", "subject": "Python", "marks": 91}, {"name": "John", "subject": "Java", "marks": 70}, ] # 1. Every student and every subject, without repeats students = {r["name"] for r in records} subjects = {r["subject"] for r in records} print(sorted(students)) # ['John', 'Kiran', 'Ravi'] print(sorted(subjects)) # ['Java', 'Python', 'SQL'] # 2. Python marks by student python_marks = {r["name"]: r["marks"] for r in records if r["subject"] == "Python"} print(python_marks) # {'Ravi': 78, 'Kiran': 45, 'John': 91} # 3. Total marks per student: for each name, add up that student's marks totals = {name: sum(r["marks"] for r in records if r["name"] == name) for name in sorted(students)} print(totals) # {'John': 161, 'Kiran': 107, 'Ravi': 163} # 4. Pass or fail per student print({name: "pass" if total >= 150 else "fail" for name, total in totals.items()}) # {'John': 'pass', 'Kiran': 'fail', 'Ravi': 'pass'} # 5. Took Python but not SQL took_python = {r["name"] for r in records if r["subject"] == "Python"} took_sql = {r["name"] for r in records if r["subject"] == "SQL"} print(took_python - took_sql) # {'John'}

Key points

  • Curly braces with key: value build a dictionary; with a single expression they build a set.
  • Read it from the for: "name maps to len(name), for each name in names".
  • Loop over d.items() to get each key and value from an existing dictionary.
  • Filter with if at the end; choose a value with if/else at the front - the same rules as Lesson 21.
  • {u["id"]: u for u in users} is the lookup-by-id table in one line.
  • Inverting with {v: k for k, v in d.items()} silently loses entries when values repeat.
  • A set comprehension removes duplicates; sort it before showing it.
  • {} is an empty dict - an empty set is set().
  • There is no tuple comprehension: round brackets make a one-pass generator.
  • Counting and grouping need a loop - a comprehension with list.count() was about 900 times slower.

Quick check before you move on

What does {n: n * 2 for n in [1, 2, 3]} give?
{1: 2, 2: 4, 3: 6}.
What type is {c for c in "hello"}, and how many items does it have?
A set with 4 items - "l" appears twice in "hello", but only once in a set.
How do you get both the key and the value when building from a dictionary?
Loop over .items(): {k: v for k, v in d.items()}.
What does inverting {"a": 1, "b": 1} give?
{1: "b"} - both keys share the value 1, and the last one wins.
What does (n for n in range(3)) create?
A generator, not a tuple. Use tuple(n for n in range(3)) for a tuple.
What is type({})?
dict. An empty set is written set().

Interview questions

What are dictionary and set comprehensions?

Expressions that build a dict or a set from an iterable: {key: value for item in iterable if condition} and {expression for item in iterable if condition}. They replace the create-empty, loop, assign/add pattern, just as list comprehensions replace append.

How do you invert a dictionary, and what is the catch?

{v: k for k, v in d.items()}. It needs unique, hashable values: duplicates collapse into one key and the last one wins silently, and an unhashable value such as a list raises TypeError. For repeated values, build a dict of lists instead.

Is there a tuple comprehension in Python?

No. Parentheses around a comprehension create a generator expression, which yields values lazily and only once. tuple(expr for x in items) builds a tuple from it.

How would you build a lookup table from a list of records?

{record["id"]: record for record in records}. One pass to build it, then each lookup by id is a single step instead of a search through the list. If ids can repeat, the last record for each id wins.

When should you not use a dictionary comprehension?

For counting or grouping, where each step depends on what has already been built - a loop with get()/setdefault() or collections.Counter/defaultdict is clearer and faster. Also when dict(zip()) or dict.fromkeys() already says it, and whenever the one-liner is harder to read than the loop.

Quiz

  1. 1.

    Rewrite as a comprehension: result = {}, then for u in users: result[u["id"]] = u["name"].

  2. 2.

    What decides whether curly braces build a dict or a set?

  3. 3.

    Why is inverting a dictionary risky, and what do you do instead?

  4. 4.

    Why is {w: words.count(w) for w in words} a poor way to count?

  5. 5.

    When is dict(zip(keys, values)) better than a comprehension?

Comments

Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.

Loading comments...