What Is Dictionary Comprehension

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

What is Dictionary Comprehension?

Dictionary comprehension is a concise and elegant way to create dictionaries in Python. It's
similar to list comprehension but tailored for dictionaries, where you define key-value pairs
within curly braces {}.

Basic Syntax

Python
{key_expression: value_expression for item in iterable (optional condition)}

Use code with caution.


play_circleeditcontent_copy

● key_expression: The expression that generates the key for each dictionary entry.
● value_expression: The expression that generates the value corresponding to the key.
● iterable: The sequence (list, tuple, string, etc.) you want to iterate over.
● optional condition: A filter to include only certain items based on a condition.

Examples

1. Squaring Numbers:

Python
numbers = [1, 2, 3, 4, 5]
squares = {num: num**2 for num in numbers}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Use code with caution.


play_circleeditcontent_copy

2. Capitalizing Words:

Python
words = ["apple", "banana", "cherry"]
capitalized = {word: word.capitalize() for word in words}
print(capitalized) # Output: {'apple': 'Apple', 'banana': 'Banana', 'cherry': 'Cherry'}

Use code with caution.


play_circleeditcontent_copy

3. Filtering with a Condition:

Python
numbers = [1, 2, 3, 4, 5, 6]
even_squares = {num: num**2 for num in numbers if num % 2 == 0}
print(even_squares) # Output: {2: 4, 4: 16, 6: 36}

Use code with caution.


play_circleeditcontent_copy

4. Creating from Two Lists:

Python
keys = ["name", "age", "city"]
values = ["Alice", 30, "New York"]
person = {k: v for k, v in zip(keys, values)}
print(person) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}

Use code with caution.


play_circleeditcontent_copy

5. Counting Word Frequency:

Python
sentence = "This is a sample sentence to count word frequency"
word_counts = {word: sentence.count(word) for word in sentence.split()}
print(word_counts)

Use code with caution.


play_circleeditcontent_copy

Key Advantages

● Readability: Dictionary comprehensions make your code more compact and easier to
understand.
● Efficiency: They can be faster than traditional loop-based approaches for creating
dictionaries.
● Flexibility: You can easily incorporate conditions to filter elements.

You might also like