A dictionary comprehension creates a new dictionary by specifying key–value expressions over an iterable. The syntax is {key_expr: value_expr for item in iterable if condition}. For example, {word: len(word) for word in ["hello", "world"]} creates {"hello": 5, "world": 5}, and {k: v for k, v in pairs if v > 0} filters a sequence of key–value pairs.
Dictionary comprehensions are useful for inverting dictionaries ({v: k for k, v in d.items()}), transforming values ({k: v.upper() for k, v in d.items()}), and constructing dictionaries from computed data. Like list comprehensions, they support multiple for clauses and if filters.
Dictionary comprehensions replace the older dict() constructor pattern: dict((k, v) for k, v in pairs) is more clearly written as {k: v for k, v in pairs}. They share the same performance benefits as list comprehensions — the iteration happens in optimised C code. If duplicate keys appear, the last value wins, just like in regular dictionary construction.
Related terms: Dictionary, Comprehension, List Comprehension
Discussed in:
- Chapter 6: Data Structures — List Comprehensions