Dictionary comprehension is a concise Python pattern for creating a dictionary from an iterable. It places key and value expressions before the iteration: {expr_key: expr_value for item in iterable}. section 5.2.2
Build a title-to-description dictionary
When each task should be indexed by title, use the title as the key and the description as the value: title_dict = {task.title: task.description for task in tasks} This produces the same dictionary as a conventional loop while making the key-value mapping immediately visible. section 5.2.2
title_dict0 = {}
for task in tasks:
title_dict0[task.title] = task.description
title_dict1 = {task.title: task.description for task in tasks}
assert title_dict0 == title_dict1
Compare the conventional loop with its equivalent dictionary comprehension and verify that both produce the same result. section 5.2.2
Use dictionary comprehension when:
- An existing iterable must become a dict and its items need transformation into keys and values. section 5.2.2
- The compact expression remains clear to the intended readers; its concision can improve readability for experienced Python users. section 5.2.2
- Prefer a dict constructor when no item manipulation is needed, and use a regular for loop when expressions become complicated or loops become deeply nested. section 5.5 section 5.2.6
The pattern follows the broader comprehension family: list comprehensions create lists, dictionary comprehensions create dicts, and set comprehensions create sets. Each iterates an iterable while applying its respective construction syntax. section 5.2 section 5.2.6


