Create a dictionary with comprehension
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Dictionary comprehensions let you build a dictionary in one expression instead of writing an explicit loop. They are compact, readable when used well, and especially useful when you are transforming or filtering data.
The Basic Syntax
The pattern is:
A simple example maps numbers to their squares:
Output:
This does the same work as a loop, but keeps the dictionary-building rule in one place.
Building a Dictionary from Two Iterables
Comprehensions are often used when keys and values come from existing collections.
This is equivalent to dict(zip(keys, values)), but the comprehension form is useful when the value needs transformation too.
Filtering While Building
You can add a condition at the end.
This is one of the best use cases for dictionary comprehensions because the selection rule and the output mapping stay together.
Transforming an Existing Dictionary
You can also keep the same keys and change the values.
This is cleaner than mutating the original dictionary when you want a new result rather than an in-place update.
Swapping Keys and Values
Another common pattern is inversion:
This works only when the values are unique. If multiple original keys share the same value, later entries overwrite earlier ones.
Nested and Conditional Expressions
You can include conditional expressions inside the value expression itself:
This is still readable because the rule is small. Once the logic becomes much more complex, a normal loop is usually better.
Equivalent Loop Form
It helps to see what the comprehension expands to:
The comprehension is not magic. It is just a shorter way to express this dictionary-building pattern.
When Not to Use One
Comprehensions are best when the mapping rule is short and obvious. If you need multiple branches, logging, exception handling, or several nested conditions, a plain loop is easier to debug and maintain.
Readable code matters more than saving a few lines.
Common Pitfalls
Forgetting that duplicate keys overwrite previous values can produce surprising results.
Packing too much logic into one comprehension makes it harder to read than the loop it replaced.
Using a comprehension when dict(zip(...)) is simpler can make code look more clever than necessary.
Assuming the comprehension preserves every source item even when multiple items generate the same key is incorrect.
Summary
- Dictionary comprehensions use the form
key: value for .... - They are great for concise transformation and filtering.
- They work well for building dictionaries from iterables or existing mappings.
- Duplicate keys do not accumulate; later values replace earlier ones.
- If the rule becomes hard to read, switch back to a normal loop.

