Dictionary comprehensions in Python build a new dictionary from an existing iterable in a single line. A dictionary comprehension is the dictionary equivalent of a list comprehension: where a list comprehension produces a list by evaluating an expression for every item, a dictionary comprehension produces a dictionary by evaluating both a key expression and a value expression for every item. The result is a fully formed dictionary, ready for lookups, without the boilerplate of creating an empty dict and assigning entries inside a loop.
If you have read about list comprehensions in Python, the pattern will feel immediately familiar. Both use the same for-in syntax inside a pair of brackets, both support an optional if filter at the end, and both tend to be faster than the equivalent loop because the interpreter avoids the repeated attribute lookup and function call overhead of calling append or assigning a key on every iteration. The only difference is that a dictionary comprehension uses curly braces and produces key-value pairs separated by a colon, while a list comprehension uses square brackets and produces individual values. The article on accessing and updating dictionaries in Python covers the dictionary operations that comprehensions produce, so you will recognize the resulting data structure.
The basic dictionary comprehension
A dictionary comprehension sits inside curly braces and has four parts: a key expression, a colon, a value expression, a for clause that defines the source of items, and an optional if clause for filtering. The simplest form maps each item in an iterable to a key-value pair.
squares = {x: x ** 2 for x in range(6)}This single line creates the dictionary {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}. Each number from the range becomes a key, and its square becomes the associated value. The equivalent loop would span four lines: create an empty dictionary, start a for loop, assign each entry, and then the variable holds the result. The comprehension collapses all of that into one expression that reads as "map each x to x squared."
The key and value expressions are independent and can be any valid Python expression. You can call functions, combine strings, perform arithmetic, or create nested structures. The for clause can iterate over any iterable: a list, a string, a range, the keys of another dictionary, the lines of a file, or the result of any function that returns an iterable.
Transforming existing dictionaries
One of the most common uses of dictionary comprehensions is transforming an existing dictionary into a new one. By iterating over the items of the original dictionary, you can modify the keys, modify the values, swap them, or filter out entries that do not meet a condition.
prices = {"apple": 0.50, "banana": 0.30, "cherry": 0.75}
doubled = {k: v * 2 for k, v in prices.items()}This comprehension doubles every price while keeping the same keys. The items method returns key-value pairs as tuples, and the for clause unpacks each tuple into k and v directly in the loop header. The key expression is simply k, preserving the original keys, and the value expression multiplies v by 2. The result is a new dictionary with the same keys and doubled values; the original dictionary is unchanged.
Swapping keys and values is another common transformation. Write the value expression as the key and the key expression as the value, and iterate over items as before. The only caution is that dictionary keys must be unique. If the original dictionary has duplicate values, only the last key encountered for each value survives in the swapped result. This is a property of dictionaries, not of comprehensions, and it means swapping works best when values are known to be distinct.
Filtering with an if clause
Adding an if clause to the end of a dictionary comprehension filters the source items. Only items that satisfy the condition produce entries in the result. This is the same filtering behavior as list comprehensions, and the if clause is written in the same position, after the for clause and before the closing brace.
Filtering is particularly useful when you want to extract a subset of a dictionary based on a condition applied to the keys or the values. You can keep only entries where the value exceeds a threshold, where the key starts with a certain prefix, or where both key and value satisfy separate conditions combined with logical operators.
When to use a regular loop
Dictionary comprehensions are powerful but they are not appropriate for every situation. When the logic for computing keys or values is complex, when you need to handle exceptions during construction, or when the comprehension spans multiple lines with deeply nested for and if clauses, a regular for loop is clearer. Readability is the deciding factor. A four-line loop that anyone can understand is better than a one-line comprehension that requires careful study.
Comprehensions also build the entire dictionary in memory. If you are processing an extremely large data source and only need to access entries one at a time, a generator expression that yields key-value pairs may be more memory-efficient. For most beginner and intermediate use cases, however, dictionary comprehensions are the right tool. They are idiomatic Python, they run faster than equivalent loops, and they communicate the intent of building a mapping directly.
For scenarios where the values in your new dictionary are themselves collections, the article on nested dictionaries in Python covers how to create and work with multi-level dictionary structures, including how comprehensions can build them efficiently.
Rune AI
Key Insights
- A dictionary comprehension has the form {key: value for item in iterable if condition}.
- The key and value expressions are evaluated for every item that passes the optional if filter.
- Iterating over dict.items() in a comprehension lets you transform one dictionary into another.
- Use a regular for loop when the logic is complex or when readability would suffer.
- Dictionary comprehensions are often faster than equivalent loops because they avoid repeated lookup overhead on each iteration.
Frequently Asked Questions
What is a dictionary comprehension?
Can I use an if clause in a dictionary comprehension?
Can I build a dictionary by swapping keys and values from an existing dict?
Conclusion
Dictionary comprehensions are the Pythonic way to build dictionaries from existing data. They replace multi-line loop-and-assign patterns with a single expression, and they pair naturally with the items view when transforming one dictionary into another.
More in this topic
Define and Call Python Functions
Learn the exact syntax for defining and calling Python functions with the def keyword, including naming rules, the function body, and how the call stack works.
Python Function Parameters and Arguments
Learn the difference between parameters and arguments, how to pass values by position and by keyword, and the rules for default parameter values.
Python Functions Explained
Learn what Python functions are, why they matter for organizing code, and how they form the foundation of non-trivial programs.