Series: Learning Python: A Comprehensive Beginner Level Tutorial Series πŸš€

Python Dictionary Comprehension

Explore Python's dictionary comprehensions. Our comprehensive guide covers concise syntax, key-value pair creation, and practical examples for efficient dictionary manipulation
E
Edtoksβ€’2:37 min read

Dictionary comprehensions are a concise way to create dictionaries in Python. They allow you to generate new dictionaries by applying an expression to each item in an existing iterable and optionally filtering the items based on a condition. Dictionary comprehensions are similar to list comprehensions but produce dictionaries instead of lists. They are a powerful tool for creating dictionaries efficiently.

Here's the basic syntax of a dictionary comprehension:

new_dict = {key_expression: value_expression for item in iterable if condition}

key_expression: The expression to compute the keys for the new dictionary.

value_expression: The expression to compute the values for the new dictionary.

item: A variable that represents the current item in the iterable.

iterable: The existing iterable from which elements are taken.

condition (optional): An optional filter that determines whether an item is included in the new dictionary.

Now, let's explore some examples to illustrate how dictionary comprehensions work:

Example 1: Creating a Dictionary of Squares

# Using a for loop
squares = {}
for x in range(1, 6):
    squares[x] = x**2

# Using a 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}

In this example, we create a dictionary where the keys are numbers from 1 to 5, and the values are their squares using both a for loop and a dictionary comprehension. The dictionary comprehension is more concise.

Example 2: Filtering Even Numbers

# Using a for loop
even_squares = {}
for x in range(1, 11):
    if x % 2 == 0:
        even_squares[x] = x**2

# Using a dictionary comprehension
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, we use a dictionary comprehension to filter even numbers from 1 to 10 and create a dictionary of their squares.

Example 3: Creating a Dictionary from Lists

names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]

# Using a dictionary comprehension
score_dict = {name: score for name, score in zip(names, scores)}

print(score_dict)  # Output: {'Alice': 85, 'Bob': 92, 'Charlie': 78}

In this example, we create a dictionary by pairing names with scores using a dictionary comprehension and theΒ zip function.

Example 4: Using a Condition to Modify Values

data = {"a": 1, "b": 2, "c": 3, "d": 4}
threshold = 2

# Using a dictionary comprehension with conditional expression
filtered_data = {key: value if value >= threshold else 0 for key, value in data.items()}

print(filtered_data)  # Output: {'a': 0, 'b': 2, 'c': 3, 'd': 4}

Here, we use a dictionary comprehension with a conditional expression to filter values in the dictionary and set values below a threshold to 0.

Dictionary comprehensions provide an elegant and efficient way to create dictionaries by transforming or filtering items from an iterable. They are a valuable tool for creating dictionaries from existing data or applying transformations to dictionary items.