Python Dictionary Comprehensions: For Creating Dictionaries in a Compact Form
Introduction to Python Dictionary Comprehension
Dictionary comprehensions in Python provide a concise way to create dictionaries. They allow for the creation of dictionaries from an iterable or another dictionary in a single line of code, making your code more readable and efficient. Here we covered creating dictionaries, filtering items, handling nested loops, inverting dictionaries, merging lists, applying functions, and including conditional logic. With these examples, you should be able to write more concise and readable Python code using dictionary comprehensions.
Basic Dictionary Comprehension:
A basic dictionary comprehension creates a dictionary by applying an expression to each item in an iterable.
Example 1: Creating a Dictionary of Squares
This example shows how to create a dictionary where the keys are numbers and the values are the squares of those numbers using dictionary comprehension.
Code:
# Create a dictionary where keys are numbers and values are their squares
squares = {x: x**2 for x in range(6)}
# Print the dictionary
print(squares)
Output:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Explanation:
The dictionary comprehension iterates over the range of numbers from 0 to 5. For each number 'x', it assigns 'x' as the key and 'x**2' as the value. The result is a dictionary where each number is paired with its square.
Filtering with Dictionary Comprehensions:
Just like list comprehensions, dictionary comprehensions can include an if condition to filter out certain items.
Example 2: Filtering Even Squares
This example demonstrates how to create a dictionary of squares for even numbers only using dictionary comprehension with a filter.
Code:
# Create a dictionary of squares for even numbers only
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
# Print the dictionary
print(even_squares)
Output:
{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Explanation:
The dictionary comprehension iterates over numbers from 0 to 9, but only includes numbers that satisfy the condition 'x % 2 == 0' (i.e., even numbers). The result is a dictionary where the keys are even numbers and the values are their squares.
Dictionary Comprehensions with Nested Loops:
Dictionary comprehensions can also be used with nested loops to generate dictionaries from combinations of items.
Example 3: Creating a Multiplication Table
This example shows how to create a multiplication table using dictionary comprehension with nested loops.
Code:
# Create a multiplication table as a dictionary of tuples
multiplication_table = {(x, y): x * y for x in range(1, 4) for y in range(1, 4)}
# Print the multiplication table
print(multiplication_table)
Output:
{(1, 1): 1, (1, 2): 2, (1, 3): 3, (2, 1): 2, (2, 2): 4, (2, 3): 6, (3, 1): 3, (3, 2): 6, (3, 3): 9}
Explanation:
The dictionary comprehension uses two nested loops: one iterating over 'x' and the other over 'y', both ranging from 1 to 3. The keys are tuples '(x, y)' representing the pairs of numbers, and the values are the products of those numbers. The result is a dictionary that acts as a multiplication table.
Inverting a Dictionary:
Dictionary comprehensions can be used to invert a dictionary, swapping its keys and values.
Example 4: Inverting a Dictionary
This example demonstrates how to invert a dictionary using dictionary comprehension.
Code:
# Original dictionary
original = {'x': 100, 'y': 200, 'z': 300}
# Invert the dictionary (swap keys and values)
inverted = {v: k for k, v in original.items()}
# Print the inverted dictionary
print(inverted)
Output:
{100: 'x', 200: 'y', 300: 'z'}
Explanation:
The dictionary comprehension iterates over the key-value pairs in the 'original' dictionary using 'original.items()'. It then swaps the keys and values, creating a new dictionary where the original values are now the keys, and the original keys are now the values.
Merging two Lists into a Dictionary:
We can use dictionary comprehensions to merge two lists into a dictionary, with one list providing the keys and the other providing the values.
Example 5: Merging Two Lists
This example shows how to merge two lists into a dictionary using dictionary comprehension.
Code:
# Two lists: one of keys and one of values
keys = ['name', 'age', 'city']
values = ['Domenica Iva', 28, 'New York']
# Merge the lists into a dictionary
merged_dict = {keys[i]: values[i] for i in range(len(keys))}
# Print the merged dictionary
print(merged_dict)
Output:
{'name': 'Domenica Iva', 'age': 28, 'city': 'New York'}
Explanation:
The dictionary comprehension iterates over the range of indices for the lists 'keys' and 'values'. For each index 'i', it pairs 'keys[i]' with 'values[i]' to create key-value pairs in the 'merged_dict'. The result is a dictionary where each key from the 'keys' list is associated with the corresponding value from the 'values' list.
Using Functions in Dictionary Comprehensions:
We can also apply functions to the values while creating dictionaries using dictionary comprehensions.
Example 6: Applying a Function to Values
This example demonstrates how to apply a function to the values in a dictionary using dictionary comprehension.
Code:
# Function to double a number
def double(x):
return x * 2
# Dictionary of numbers
numbers = {'a': 100, 'b': 200, 'c': 300}
# Create a new dictionary with doubled values
doubled = {k: double(v) for k, v in numbers.items()}
# Print the dictionary with doubled values
print(doubled)
Output:
{'a': 200, 'b': 400, 'c': 600}
Explanation:
The dictionary comprehension iterates over the key-value pairs in 'numbers'. For each pair, it applies the double() function to the value 'v', creating a new dictionary where the values are 'doubled'.
Handling Conditional Logic in Dictionary Comprehensions:
We can include conditional logic within a dictionary comprehension to modify the values or keys based on certain conditions.
Example 7: Creating a dictionary with conditional values
This example shows how to include conditional logic in a dictionary comprehension to create a dictionary that categorizes numbers as even or odd.
Code:
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Create a dictionary with even numbers as keys and 'Even' as values, odd numbers as keys and 'Odd' as values
even_odd = {x: 'Even' if x % 2 == 0 else 'Odd' for x in numbers}
# Print the dictionary
print(even_odd)
Output:
{1: 'Odd', 2: 'Even', 3: 'Odd', 4: 'Even', 5: 'Odd'}
Explanation:
The dictionary comprehension iterates over the list 'numbers'. For each number 'x', it checks if the number is even or odd using the condition 'x % 2 == 0'. Depending on the result, it assigns either 'Even' or 'Odd' as the value in the 'even_odd' dictionary.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics