Python Dictionary Comprehensions
Table of Contents
In the last lesson, we learned about Python Nested Dictionaries. Now let’s create new dictionaries with short, clear comprehensions.
Let’s Talk About Building Dictionaries Quickly
We know how to create a dictionary. We write out the key-value pairs.
squares = {1: 1, 2: 4, 3: 9, 4: 16}That works. But what if we want to build a dictionary from some data? Like a list of numbers? Or from another dictionary?
We could write a loop.
numbers = [1, 2, 3, 4, 5]squares = {}for n in numbers: squares[n] = n * nprint(squares)Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}That works. But it takes four lines. And it is a bit repetitive.
Python has a shortcut for this. It is called a dictionary comprehension.
What Is a Dictionary Comprehension in Python?
A dictionary comprehension is a way to create a dictionary in one line. We describe what keys and values we want. And Python builds the dictionary for us.
It is just like a list comprehension, but for dictionaries.
The Basic Syntax of Python Dictionary Comprehension
{key_expression: value_expression for item in iterable}key_expression— what we want as the keyvalue_expression— what we want as the valueitem— the variable that takes each value from the iterableiterable— the sequence we are looping over
Let’s see a simple example.
numbers = [1, 2, 3, 4, 5]squares = {n: n * n for n in numbers}print(squares)Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}One line. Same result. Much cleaner.
Adding a Condition to Python Dictionary Comprehension
We can add an if to filter items. Only items that satisfy the condition are included.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]even_squares = {n: n * n for n in numbers if n % 2 == 0}print(even_squares)Output
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}Only even numbers are included. The odd ones are skipped.
We can use any condition.
words = ["apple", "banana", "cherry", "date"]long_words = {w: len(w) for w in words if len(w) > 5}print(long_words)Output
{'banana': 6, 'cherry': 6}If and Else in Python Dictionary Comprehension
We can also use if and else together. But the syntax is a bit different. The if-else goes before the for.
numbers = [1, 2, 3, 4, 5]labels = {n: ("even" if n % 2 == 0 else "odd") for n in numbers}print(labels)Output
{1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd'}Here, for each number, we choose the label “even” or “odd”. The condition is n % 2 == 0. If true, “even”. If false, “odd”.
That is the ternary operator inside a comprehension. It works, but let’s not make it too complex.
Building a Dictionary from Two Lists in Python
A very common use case is building a dictionary from two lists. One list of keys. One list of values.
keys = ["name", "age", "city"]values = ["Alex", 25, "London"]
person = {k: v for k, v in zip(keys, values)}print(person)Output
{'name': 'Alex', 'age': 25, 'city': 'London'}The zip() function pairs up the items from both lists. Then the comprehension builds the dictionary.
That is a very handy pattern.
Swapping Keys and Values in Python Dictionary Comprehension
We can swap keys and values in a dictionary.
original = {"a": 1, "b": 2, "c": 3}swapped = {v: k for k, v in original.items()}print(swapped)Output
{1: 'a', 2: 'b', 3: 'c'}That is a clean way to invert a dictionary. Just let’s be careful if values are not unique. Because keys must be unique.
Filtering a Dictionary in Python
We can filter a dictionary based on conditions.
scores = {"Alex": 85, "Sam": 92, "John": 78, "Emma": 95}high_scores = {name: score for name, score in scores.items() if score >= 90}print(high_scores)Output
{'Sam': 92, 'Emma': 95}Only the students with scores 90 or above are included.
Transforming Values in Python Dictionary Comprehension
We can transform values while building a new dictionary.
prices = {"apple": 1.50, "banana": 0.75, "cherry": 3.00}discounted = {item: price * 0.9 for item, price in prices.items()}print(discounted)Output
{'apple': 1.35, 'banana': 0.675, 'cherry': 2.7}Every price is reduced by 10%.
Python Dictionary Comprehension: A Real-Life Example
Let’s say we have a list of words. And we want to build a dictionary where the word is the key and the length is the value. But only for words longer than 3 characters.
words = ["cat", "elephant", "dog", "butterfly", "ant"]word_lengths = {word: len(word) for word in words if len(word) > 3}print(word_lengths)Output
{'elephant': 8, 'butterfly': 9}That is clean and easy.
Another Example — Counting Characters
text = "hello"char_count = {char: text.count(char) for char in set(text)}print(char_count)Output
{'h': 1, 'e': 1, 'l': 2, 'o': 1}We use set(text) to get unique characters. Then for each character, we count how many times it appears.
That is a nice one-liner.
Nested Dictionary Comprehension in Python
We can have a dictionary comprehension inside another. But let’s be careful. It can get confusing.
matrix = [[1, 2], [3, 4], [5, 6]]flat = {i: j for i, row in enumerate(matrix) for j in row}print(flat)Output
{0: 2, 1: 4, 2: 6}Wait. That is not what we might expect. Let me explain.
The enumerate(matrix) gives (0, [1,2]), (1, [3,4]), (2, [5,6]).
For each pair, we loop over row. So for the first row, i=0, and j takes 1 and 2. The dictionary gets 0: 1 then 0: 2. The last one wins. So 0 ends up with 2.
Then i=1, j takes 3 and 4. So 1: 4. And so on.
So the result is {0: 2, 1: 4, 2: 6}. That is probably not what we wanted. But it shows how nested comprehensions work.
For flattening, we would just use a list comprehension. Dictionary comprehensions are for creating dictionaries.
When to Use Dictionary Comprehensions in Python
Use them when:
- We are building a new dictionary from an iterable.
- The logic is simple (one key expression, one value expression, maybe one condition).
- We want cleaner, more readable code.
Do not use them when:
- The logic is complex.
- We need multiple statements.
- The comprehension becomes hard to read.
Readability matters more than shortness. If a loop is clearer, let’s use a loop.
Common Mistakes with Python Dictionary Comprehensions
Mistake 1: Forgetting the Colon Between Key and Value
squares = {n n * n for n in numbers} # Error!So what do we do? We add the colon.
squares = {n: n * n for n in numbers}Mistake 2: Using the Wrong Order for if-else
labels = {n: if n % 2 == 0 "even" else "odd" for n in numbers} # Error!So what do we do? We put the expression first.
labels = {n: ("even" if n % 2 == 0 else "odd") for n in numbers}Mistake 3: Forgetting That Keys Must Be Unique
words = ["apple", "banana", "apple"]lengths = {w: len(w) for w in words}print(lengths)Output
{'apple': 5, 'banana': 6}The second “apple” overwrote the first. Because keys must be unique. So the final value is from the last occurrence.
Mistake 4: Trying to Do Too Much
result = {k: v for k in list1 for v in list2 if k > 0 if v < 10}This is technically valid but unreadable. Let’s break it into smaller steps or use loops.
Next, we will learn about Iterating Through Python Dictionaries and loop through keys and values.