A dict comprehension follows the same shape as a list comprehension, but produces key-value pairs instead of single values, using a colon to separate the key expression from the value expression. It's commonly used to transform an existing dict, like swapping keys and values or filtering entries, or to build a dict from two related sequences, such as pairing up a list of keys with a list of computed values.
1Understanding Dictionary Comprehensions
A dict comprehension follows the same shape as a list comprehension, but produces key-value pairs instead of single values, using a colon to separate the key expression from the value expression. It's commonly used to transform an existing dict, like swapping keys and values or filtering entries, or to build a dict from two related sequences, such as pairing up a list of keys with a list of computed values.
Swapping a dict's keys and values with a comprehension only works cleanly if the original values are unique and hashable — if two keys share the same value, the swap silently loses one of them, since dict keys must be unique.
names = ["Alice", "Bob", "Carol"]
name_lengths = {name: len(name) for name in names}
print(name_lengths)2Practical Example
Here is a real-world application of Dictionary Comprehensions showing how it is used in production Python code.
prices = {"apple": 1.5, "banana": 0.5, "cherry": 3.0}
expensive = {item: price for item, price in prices.items() if price > 1}
print(expensive)3Best Practices
Follow these guidelines when working with Dictionary Comprehensions:
1. Use a dict comprehension instead of a for loop with manual key assignment when building a dict from a transformation of another iterable
2. Use it to filter an existing dict's entries by key or value, instead of manually building a new dict and copying matching entries over
3. Watch out for duplicate keys/values when transforming a dict with a comprehension — later entries silently overwrite earlier ones with the same key
Tip: Swapping a dict's keys and values with a comprehension only works cleanly if the original values are unique and hashable — if two keys share the same value, the swap silently loses one of them, since dict keys must be unique.
names = ["Alice", "Bob", "Carol"]
name_lengths = {name: len(name) for name in names}
print(name_lengths)