Python Dictionary Comprehension
Dictionary comprehension is a quick and simple way to create dictionaries in a single line of code. It creates key-value pairs by iterating through an iterable (like a list, tuple, or range), and you can include a condition to include only certain items.
Basic Syntax
{key_expression: value_expression for item in iterable if condition}
Where,
key_expression: Defines how keys are created.
value_expression: Defines how values are created.
item: Loop variable that takes each value from the iterable during the iteration.
iterable: Any iterable object, such as a list, tuple, string, range, or another dictionary.
if condition (Optional): A conditional statement that filters items from the iterable before adding them to the new dictionary. Only the items that meet the condition (i.e., where the condition evaluates to True) are included.
Example: Create a Dictionary of Squares
squares = {x: x**2 for x in range(5)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Example: Create a Dictionary From Two Lists
keys = ["name", "age", "location"]
values = ["James", 30, "London"]
person = {k:v for k, v in zip(keys, values)}
print(person) # Output: {'name': 'James', 'age': 30, 'location': 'London'}
Example: Creating a New Dictionary With Updated Values
Suppose we have a dictionary containing fruit names and their current prices. Due to inflation, the prices of all fruits have increased by 15%. Let’s create a new dictionary that reflects these updated prices.
For example:
fruits_old_prices = {"apple": 1.5, "banana": 2.39, "mango": 3.89}
# Increase each fruit price by 15%
fruits_new_prices = {key: value * 1.15 for key, value in fruits_old_prices.items()}
print(fruits_new_prices)
# Output: {'apple': 1.7249999999999999, 'banana': 2.7485, 'mango': 4.4735}
If you want the prices rounded to two decimal places, you can use the round() function as follows:
fruits_new_prices = {key: round(value * 1.15, 2) for key, value in fruits_old_prices.items()}
# Rounded Output: {'apple': 1.72, 'banana': 2.75, 'mango': 4.47}
Conditional Logic With Dictionary Comprehension
You can add an if statement at the end of a dictionary comprehension to include only the key-value pairs that satisfy a specific condition from the original dictionary.
For example:
Suppose we have a dictionary containing people’s names and their ages. We want to create a new dictionary that includes only the adults (those who are 18 and older). Here is how you can achieve this using a dictionary comprehension with a conditional filter:
people = {"kevin": 16, "james": 30, "lisa": 15, "sarah": 20, "mark": 18}
adult = {key: value for key, value in people.items() if value >= 18}
print(adult) # OUtput: {'james': 30, 'sarah': 20, 'mark': 18}
if-else in Dictionary Comprehension
To modify values based on a condition, you can use a ternary if-else expression directly within the expression part of the dictionary comprehension.
For example:
Suppose we have a list of numbers, and we want to create a dictionary that labels each number as either "even" or "odd". We can accomplish this using a dictionary comprehension with an if-else statement.
numbers = [5, 6, 9, 10, 15]
number_labels = {num: ("even" if num % 2 == 0 else "odd") for num in numbers}
print(number_labels)
# Output: {5: 'odd', 6: 'even', 9: 'odd', 10: 'even', 15: 'odd'}
Nested Dictionary Comprehension
A nested dictionary comprehension occurs when one dictionary comprehension is used inside another.
Example: Create a Multiplication Table
# Create a multiplication table from 1 to 5
multiplication_table = {i: {j: i * j for j in range(1, 6)} for i in range(1, 5)}
print(multiplication_table)
Output:
{
1: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5},
2: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10},
3: {1: 3, 2: 6, 3: 9, 4: 12, 5: 15},
4: {1: 4, 2: 8, 3: 12, 4: 16, 5: 20}
}
In this example, the outer loop (for i range(1, 5)) iterates through the numbers 1 to 4. Each of these numbers becomes a key in the outer dictionary, representing the rows of the multiplication table.
The inner loop (for j in range(1, 6)) iterates through the numbers 1 to 5 for each i. For each pair (i, j), it calculates the product i * j and stores it as a key-value pair in the inner dictionary.
The result is a nested dictionary where each outer key maps to an inner dictionary containing that number’s multiplication results from 1 to 5.
Note: In a nested dictionary comprehension, the outer loop runs first and selects one key at a time, and for each key from the outer loop, the inner loop runs completely to generate the inner dictionary before the outer loop moves to the next key.