Dictionary Comprehension in Python
What is Dictionary Comprehension?
Dictionary comprehension is a concise and efficient way to create dictionaries in Python using a single line of code. It follows a syntax similar to list comprehension but constructs key-value pairs instead.
Basic Syntax of Dictionary Comprehension
{key_expression: value_expression for item in iterable if condition}
{}
: Curly brackets indicate a dictionary.key_expression
: The expression used to generate dictionary keys.value_expression
: The expression used to generate dictionary values.for item in iterable
: Iterates through an iterable (list, tuple, range, etc.).if condition
: (Optional) Filters elements based on a condition.
1. Creating a Dictionary Using Comprehension
Example: Squaring numbers from 1 to 5 and storing them as key-value pairs.
squares = {x: x**2 for x in range(1, 6)}
print(squares)
Output:
Here,
x
is the key,x**2
is the value.
2. Adding Conditions in Dictionary Comprehension
Example: Create a dictionary with only even numbers squared.
even_squares = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(even_squares)
Output:
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
Explanation:
if x % 2 == 0
ensures only even numbers are included.
3. Swapping Keys and Values
Example: Reverse key-value pairs in an existing dictionary.
original_dict = {'a': 1, 'b': 2, 'c': 3}
swapped_dict = {v: k for k, v in original_dict.items()}
print(swapped_dict)
Output:
{1: 'a', 2: 'b', 3: 'c'}
Explanation:
.items()
provides key-value pairs.v: k
swaps keys and values.
4. Using Nested Loops in Dictionary Comprehension
Example: Creating a dictionary of multiplication tables.
multiplication_table = {f"{i}x{j}": i * j for i in range(1, 4) for j in range(1, 4)}
print(multiplication_table)
Output:
{'1x1': 1, '1x2': 2, '1x3': 3, '2x1': 2, '2x2': 4, '2x3': 6, '3x1': 3, '3x2': 6, '3x3': 9}
Explanation:
- Two loops iterate over
i
andj
to generate key-value pairs.
5. Using Dictionary Comprehension with Functions
Example: Convert a list of words to a dictionary with word lengths.
words = ["apple", "banana", "cherry"]
word_lengths = {word: len(word) for word in words}
print(word_lengths)
Output:
{'apple': 5, 'banana': 6, 'cherry': 6}
Explanation:
word
is the key.len(word)
is the value.
6. Handling Duplicate Values in Dictionary Comprehension
Since dictionaries don’t allow duplicate keys, if a key appears multiple times, the last value is retained.
Example: Creating a dictionary with duplicate keys.
nums = [1, 2, 2, 3, 3, 3]
duplicate_handling = {num: num**2 for num in nums}
print(duplicate_handling)
Output:
{1: 1, 2: 4, 3: 9}
Explanation:
2
and3
appear multiple times, but only the last occurrence is kept.
7. Dictionary Comprehension with zip()
Example: Merging two lists into a dictionary.
keys = ["name", "age", "city"]
values = ["Alice", 25, "New York"]
person_dict = {k: v for k, v in zip(keys, values)}
print(person_dict)
Output:
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Explanation:
zip(keys, values)
pairs elements from both lists.
8. Nested Dictionary Comprehension
Example: Creating a matrix using dictionary comprehension.
matrix = {i: {j: i * j for j in range(1, 4)} for i in range(1, 4)}
print(matrix)
Output:
{1: {1: 1, 2: 2, 3: 3}, 2: {1: 2, 2: 4, 3: 6}, 3: {1: 3, 2: 6, 3: 9}}
Explanation:
- Each
i
key has another dictionary as a value.
9. Using Dictionary Comprehension with if-else
Conditions
Example: Categorizing numbers as “even” or “odd”.
numbers = range(1, 6)
number_type = {num: ("even" if num % 2 == 0 else "odd") for num in numbers}
print(number_type)
Output:
{1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd'}
Explanation:
- The ternary expression
("even" if num % 2 == 0 else "odd")
assigns categories.
Advantages of Dictionary Comprehension
- Concise Code – Reduces multiple lines of loops into one.
- Improved Readability – More expressive than traditional loops.
- Better Performance – Faster than using
for
loops withdict.update()
.
When to Avoid Dictionary Comprehension?
- If the logic inside the comprehension is too complex, it may reduce readability.
- When dealing with very large datasets, using comprehensions might lead to high memory usage.
Conclusion
Dictionary comprehension is a powerful tool that makes it easy to create dictionaries efficiently. By mastering it, you can write cleaner, more efficient Python code.