Build Indexes with Dictionary Comprehensions
Core idea
A dictionary comprehension uses {key_expression: value_expression for item in iterable}. It evaluates a key and a value for each selected item. Like ordinary dictionary assignment, a repeated equal key receives the latest value. Keys must be hashable.
labels = ["A7", "B12", "C"]lengths = {label: len(label) for label in labels}print(lengths)Each label becomes a key, and its length becomes the corresponding value.
Build a lookup from pairs
rows = [("desk", 2), ("lamp", 4), ("desk", 5)]stock = {name: count for name, count in rows}print(stock)The final desk count replaces the earlier count without moving the key.
Filter entries
stock = {"pen": 0, "pad": 3, "clip": 8}print({name: count for name, count in stock.items() if count > 0})The items view supplies key-value pairs; the filter keeps only positive counts.
Common mistake
A dictionary comprehension does not collect every value for a repeated key. If you need groups of values, use a loop and the grouping pattern from the dictionary chapter.
Practice
Build a lookup of product codes and quantities from pairs, including one repeated code. Predict the final value before running.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dictionary transformations
Check your understanding of dictionary comprehensions.
What is printed?
print({s: len(s) * 2 for s in ["a", "bb"]})What is printed?
print({k: v for k, v in [("x", 1), ("x", 7)]})What is printed?
d = {"a": 0, "b": 3}print({k: v for k, v in d.items() if v > 0})What separates the key expression from the value expression?