Python Dictionary Comprehensions Explained with Examples

A practical beginner guide to Python dictionary comprehensions. Learn the syntax, the filter clause, the inversion pattern, and when to reach for a regular loop instead.

Pythonbeginner
7 min read

Python dictionary comprehensions are the natural next step after list comprehensions. The same compact shape, the same expression then loop then optional filter pattern, just producing key value pairs instead of single values. They show up across real Python code whenever you need to derive a new dictionary from existing data, and learning the shape pays off whether you are building configuration maps, indexing lookups, or transforming data between formats.

The Shape of a Dictionary Comprehension

A dictionary comprehension lives inside curly braces rather than square brackets. The head expression is now a key value pair written as expression colon expression, followed by a for clause and an optional if clause. Reading the head as the rule for building each entry, the for clause as the iteration, and the if clause as the filter is exactly the same workflow that applied to list comprehensions, just adapted for the two-part shape of dictionary entries.

pythonpython
squares = {n: n * n for n in range(5)}

The example above produces a dictionary that maps each number from zero to four to its square. The head is the pair n colon n times n, the for clause iterates over the range, the if clause is absent. The result is a dictionary with five entries that you can index by any of the keys. The mental model from list comprehensions transfers directly. To revisit how dictionaries themselves work as a data type, our walkthrough on Python dictionaries explained with real-world examples covers the underlying type the comprehension produces.

Filtering Entries

The optional if clause filters the entries that make it into the resulting dictionary. The condition is evaluated for each iteration, and only iterations whose condition is true contribute a key value pair to the result. The condition can reference the loop variable directly or read from the keys and values of any source dictionary you are iterating.

pythonpython
scores = {"mira": 91, "sara": 82, "anil": 73}
high = {name: score for name, score in scores.items() if score >= 80}

The example above produces a new dictionary that includes only the entries whose score is eighty or higher. The for clause uses tuple unpacking to bind both the key and the value of each entry. The if clause then references the value directly. Using the items method of the source dictionary is the most common pattern when the comprehension needs both the key and the value, and it works the same way inside any kind of comprehension. For a closer picture of how list comprehensions sit next to dictionary comprehensions, our piece on Python list comprehensions explained step by step pairs naturally with this one.

Inverting a Dictionary

One of the most useful patterns that dictionary comprehensions enable is inverting a dictionary, which means swapping the keys and the values. This is something you reach for whenever a forward lookup needs a reverse counterpart, or when an indexing table needs to be flipped for a different access pattern. The shape is one line, the head simply puts the value before the colon and the key after it.

Starting from a small status code dictionary like ok mapping to 200, not_found mapping to 404, and server_error mapping to 500, a one line comprehension iterating its items and writing code before name produces the inverted dictionary. The result is a dictionary that maps the original values to the original keys. The pattern assumes that the original values were unique. If two entries share a value, the inversion keeps only one of them, because dictionary keys are unique. When the input has duplicate values, you usually want a dictionary that maps each value to a list of original keys, which is a different shape that either requires the standard library's defaultdict from collections or a regular for loop with a setdefault call. To revisit the basics of dictionary methods like items, our guide on Python functions vs methods explained clearly covers method calls in general.

When to Switch Back to a Regular Loop

Dictionary comprehensions are best on small, single-purpose transformations. The moment the head expression needs intermediate variables, the filter becomes a compound condition, or the same loop also needs to perform side effects, a regular for loop reads better. A dictionary built inside a regular loop has room for comments, helper calls, and conditional logic that does not fit neatly on a single line.

A second case where a regular loop wins is when you need to handle duplicate keys with a deliberate rule, like keeping the entry with the highest value or merging lists of associated values. Dictionary comprehensions silently overwrite earlier entries when later iterations produce the same key, which is rarely what you want when the duplicates are meaningful. A regular loop with an explicit if statement and a setdefault or an update call makes the rule visible. The third case is when the resulting dictionary is large enough that you would prefer a generator expression fed to the dict constructor, which streams pairs through one at a time and avoids building an intermediate sequence.

Frequently Asked Questions

What is the difference between a list comprehension and a dictionary comprehension in Python?

list comprehension uses square brackets and a single expression to produce each item of a new list. A dictionary comprehension uses curly braces and a key value head, written as expression colon expression, to produce each entry of a new dictionary. The for clause and optional if clause work identically. The only structural difference is the brackets and the two-part head.

How do I filter a Python dictionary with a comprehension?

Use the items method of the source dictionary in the for clause to unpack each entry into a key and a value, then add an if clause that references the variables. The resulting dictionary contains only the entries whose condition is true. This pattern replaces a longer for loop that built a new dictionary one entry at a time and is the most common reason to reach for the comprehension form.

How do I invert a Python dictionary?

Write a dictionary comprehension whose head puts the value before the colon and the key after it, iterating the source dictionary's items. The resulting dictionary maps the original values back to the original keys. The pattern assumes the original values were unique. If they were not, you need a different shape that groups duplicate values into lists, usually with defaultdict from the collections module. ### Key Takeaways - A dictionary comprehension uses curly braces, a key value head, a for clause, and an optional if clause. - The for clause typically unpacks the source dictionary's items into named key and value variables. - The if clause filters which entries contribute to the resulting dictionary. - Inverting a dictionary is a one-liner that assumes the original values are unique. - Switch back to a regular for loop whenever the head, filter, or duplicate handling needs more than one line.

Conclusion

A Python dictionary comprehension uses curly braces with a key value head, a for clause, and an optional if clause to produce a new dictionary from an iterable. The mental model is identical to the list comprehension model, just with a two-part head instead of a single expression. The two most common patterns are filtering a source dictionary down to interesting entries and inverting a dictionary to flip keys with values. The fastest way to internalise the shape is to take a small dictionary you already have and write three short comprehensions over it: one that filters by value, one that maps each key to a transformed value, and one that inverts the dictionary. After fifteen minutes of those exercises, dictionary comprehensions become a normal part of your Python rather than a piece of syntax you have to think hard about.