4.6 Dictionary Comprehensions
Dictionary comprehensions provide a concise way to create dictionaries by transforming or filtering data from an existing iterable, just like list comprehensions but for dictionaries. With dictionary comprehensions, you can quickly generate key-value pairs using a compact and readable syntax.
In this section, we'll explore how to create dictionaries using comprehensions, apply filtering conditions, and handle advanced scenarios.
4.6.1 Basic Dictionary Comprehension Syntax
A dictionary comprehension consists of curly braces {}
containing an expression for the key and value, followed by a for
clause and an optional if
clause to filter elements.
Syntax:
new_dict = {key_expression: value_expression for item in iterable if condition}
- key_expression: Expression that defines the key for each dictionary entry.
- value_expression: Expression that defines the value for each dictionary entry.
- item: The variable that takes each value from the iterable.
- iterable: The sequence to iterate over (e.g., list, tuple, dictionary).
- condition (optional): An optional filtering condition to include items in the new dictionary.
4.6.2 Examples of Dictionary Comprehensions
Example 1: Basic Dictionary Comprehension
Create a dictionary where the keys are numbers from 1 to 5, and the values are their squares.
squares = {x: x**2 for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
In this example:
- The
key_expression
isx
, and thevalue_expression
isx**2
. - The
iterable
isrange(1, 6)
.
Example 2: Dictionary Comprehension with Filtering
Create a dictionary of even numbers and their squares from 1 to 10.
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}
Here, the if
condition x % 2 == 0
filters out odd numbers, so only even numbers are included in the resulting dictionary.
4.6.3 Dictionary Comprehensions from Existing Dictionaries
You can also create a new dictionary by transforming or filtering key-value pairs from an existing dictionary.
Example 1: Transforming an Existing Dictionary
Suppose you have a dictionary of student names and their scores. You want to create a new dictionary where the keys remain the same, but the values are increased by 10 points.
students = {"Alice": 85, "Bob": 78, "Charlie": 92}
bonus_points = {name: score + 10 for name, score in students.items()}
print(bonus_points) # Output: {'Alice': 95, 'Bob': 88, 'Charlie': 102}
In this example, the dictionary comprehension iterates over the items of the students
dictionary and updates the scores.
Example 2: Filtering an Existing Dictionary
Create a dictionary of students who scored more than 80.
top_students = {name: score for name, score in students.items() if score > 80}
print(top_students) # Output: {'Alice': 85, 'Charlie': 92}
Here, only students with a score above 80 are included in the top_students
dictionary.
4.6.4 Advanced Dictionary Comprehensions
Example 1: Using Multiple for
Loops
You can use multiple for
loops inside a dictionary comprehension to create complex dictionaries based on combinations of values.
Example: Create a dictionary where the keys are tuples representing coordinate pairs, and the values are the sums of those pairs.
coordinates = {(x, y): x + y for x in range(1, 4) for y in range(1, 4)}
print(coordinates)
# Output: {(1, 1): 2, (1, 2): 3, (1, 3): 4, (2, 1): 3, (2, 2): 4, (2, 3): 5, (3, 1): 4, (3, 2): 5, (3, 3): 6}
In this example:
- The keys are tuples representing coordinate pairs
(x, y)
. - The values are the sums of
x
andy
.
Example 2: Conditional Expressions
You can use conditional expressions inside dictionary comprehensions to handle different cases for the key-value pairs.
Example: Create a dictionary where the values are labeled as "even" or "odd" based on the key.
labels = {x: "even" if x % 2 == 0 else "odd" for x in range(1, 6)}
print(labels) # Output: {1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd'}
Here, the value for each key is determined based on whether the key is even or odd.
4.6.5 Practical Use Cases for Dictionary Comprehensions
Example 1: Counting Occurrences
Suppose you have a list of words and want to count how often each word appears. You can use a dictionary comprehension to count the occurrences.
words = ["apple", "banana", "apple", "cherry", "cherry", "cherry"]
word_count = {word: words.count(word) for word in set(words)}
print(word_count) # Output: {'apple': 2, 'banana': 1, 'cherry': 3}
Example 2: Inverting a Dictionary
You can use a dictionary comprehension to swap the keys and values in a dictionary.
students = {"Alice": 85, "Bob": 78, "Charlie": 92}
inverted_students = {score: name for name, score in students.items()}
print(inverted_students) # Output: {85: 'Alice', 78: 'Bob', 92: 'Charlie'}
This can be useful when you want to look up keys by their values.
Example 3: Mapping Lists to Dictionary Keys
Suppose you have two lists, one of names and one of ages, and you want to combine them into a dictionary where each name is associated with its corresponding age.
names = ["Alice", "Bob", "Charlie"]
ages = [25, 22, 27]
name_age_dict = {name: age for name, age in zip(names, ages)}
print(name_age_dict) # Output: {'Alice': 25, 'Bob': 22, 'Charlie': 27}
Here, zip(names, ages)
pairs the elements of the two lists, and the dictionary comprehension creates key-value pairs.
4.6.6 Dictionary Comprehension vs. Traditional Loop
Using dictionary comprehensions can simplify code that would otherwise require multiple lines with a traditional loop. However, like list comprehensions, it's important to keep readability in mind and avoid overly complex comprehensions.
Example: Traditional Loop vs. Dictionary Comprehension
Traditional loop:
squares = {}
for x in range(1, 6):
squares[x] = x**2
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Equivalent dictionary comprehension:
squares = {x: x**2 for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Both methods produce the same result, but the dictionary comprehension is more concise.
4.6.7 Summary
- Dictionary comprehensions offer a concise and readable way to create dictionaries by applying expressions to items in an iterable.
- You can use filtering conditions to include only specific items in the resulting dictionary.
- Multiple
for
loops and conditional expressions enable more complex dictionary comprehensions, such as generating combinations or handling multiple cases. - Dictionary comprehensions can be used for practical tasks like inverting dictionaries, counting occurrences, and mapping lists to dictionary keys.
- While dictionary comprehensions are powerful, it's essential to balance readability and complexity when using them.
Mastering dictionary comprehensions will help you write cleaner and more efficient Python code, especially when generating or transforming dictionaries based on existing data.