Python Dictionary Comprehension
Dictionary comprehension is a concise way to create a new dictionary by applying transformations and filtering conditions to an existing iterable (such as a list, tuple, or another dictionary). It allows you to create dictionaries on a single line of code.
Syntax
{key_expression: value_expression for item in iterable if condition}
key_expression
: This expression defines the keys of the dictionary.
value_expression
: This expression defines the values of the dictionary.
for item in iterable
: This iterates over an iterable (like a list, tuple, or another dictionary).
if condition
(Optional): This filters the items based on a condition.
Example: Basic dictionary comprehension
Create a dictionary where keys are numbers and the values are their squares.
squares = {x: x**2 for x in range(1, 5)}
print(squares)
Output:
{1: 1, 2: 4, 3: 9, 4: 16}
Dictionary comprehension with condition
You can also apply conditions to filter or modify the items that are added to the dictionary.
Example: Create a dictionary of squares for even numbers only
numbers = [1, 2, 3, 4, 5, 6, 7]
squares = {x: x**2 for x in numbers if x % 2 == 0}
print(squares)
Output:
{2: 4, 4: 16, 6: 36}
Using multiple if
conditions
You can include multiple if
conditions in a dictionary comprehension to filter items based on multiple conditions.
Let’s filter a dictionary to include only even numbers that are less than 5
.
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
filtered_dict = {key: value ** 2 for key, value in my_dict.items() if value % 2 == 0 if value < 5}
print(filtered_dict)
Output:
{'b': 4, 'd': 16}
Using else
in dictionary comprehension
You can also use an else
clause to handle cases where the conditions are not met.
Let’s create a dictionary of even and odd labels for numbers:
numbers = [1, 2, 3, 4, 5]
result = {x: "even" if x % 2 == 0 else "odd" for x in numbers}
print(result)
Output:
{1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd'}
Nested dictionary comprehension
You can use nested dictionary comprehension to create nested dictionaries.
Let’s create a dictionary with square values of numbers in a nested structure.
my_dict = {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}}
squared_numbers = {outer_key: {inner_key: value ** 2 for inner_key, value in inner_dict.items()} for outer_key, inner_dict in my_dict.items()}
print(squared_numbers)
Output:
{'a': {'b': 1, 'c': 4}, 'd': {'e': 9, 'f': 16}}