Dictionary Comprehension

Loading

Dictionary comprehension is a concise way to create dictionaries in Python. It works similarly to list comprehension, but instead of generating lists, it generates dictionaries with key-value pairs.

Why Use Dictionary Comprehension?

More readable and concise than traditional loops
Faster execution compared to loops
Useful for transforming, filtering, and mapping data


1. Basic Syntax of Dictionary Comprehension

new_dict = {key_expression: value_expression for item in iterable if condition}
  • key_expression → Defines the key for the dictionary
  • value_expression → Defines the value for the dictionary
  • item → Each element from the iterable
  • iterable → Source of data (list, range, dictionary, etc.)
  • condition (optional) → Filters which items get included

2. Creating Dictionaries Using Dictionary Comprehension

Example 1: Creating a Dictionary of Squares

squares = {x: x**2 for x in range(1, 6)}
print(squares)

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Example 2: Swapping Keys and Values

original_dict = {"a": 1, "b": 2, "c": 3}
swapped_dict = {value: key for key, value in original_dict.items()}
print(swapped_dict)

Output:

{1: 'a', 2: 'b', 3: 'c'}

3. Filtering Items with Conditions

Example: Filtering Even Numbers from a Dictionary

numbers = {x: x**2 for x in range(10) if x % 2 == 0}
print(numbers)

Output:

{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Example: Creating a Dictionary of Only Vowels

text = "dictionary"
vowel_dict = {char: text.count(char) for char in text if char in "aeiou"}
print(vowel_dict)

Output:

{'i': 2, 'o': 1, 'a': 1}

4. Using if-else in Dictionary Comprehension

If you need an if-else condition, it must be inside the value expression.

Example: Assigning Even or Odd Labels

num_dict = {x: ("Even" if x % 2 == 0 else "Odd") for x in range(1, 6)}
print(num_dict)

Output:

{1: 'Odd', 2: 'Even', 3: 'Odd', 4: 'Even', 5: 'Odd'}

5. Nested Dictionary Comprehension

Example: Creating a Multiplication Table (Nested Dictionary)

multiplication_table = {x: {y: x * y for y in range(1, 6)} for x in range(1, 6)}
print(multiplication_table)

Output (Simplified View):

{
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},
5: {1: 5, 2: 10, 3: 15, 4: 20, 5: 25}
}

6. Dictionary Comprehension with zip()

zip() pairs elements from two lists, which is useful for dictionary creation.

Example: Creating a Dictionary from Two Lists

keys = ["name", "age", "city"]
values = ["Alice", 25, "New York"]

person_dict = {key: value for key, value in zip(keys, values)}
print(person_dict)

Output:

{'name': 'Alice', 'age': 25, 'city': 'New York'}

7. Counting Elements Using Dictionary Comprehension

Example: Counting Word Occurrences in a Sentence

sentence = "apple banana apple orange banana apple"
word_count = {word: sentence.split().count(word) for word in sentence.split()}
print(word_count)

Output:

{'apple': 3, 'banana': 2, 'orange': 1}

8. Performance Comparison: Dictionary Comprehension vs. Loop

Example: Using a Loop

numbers = {}
for x in range(1, 1000000):
numbers[x] = x**2

Example: Using Dictionary Comprehension

numbers = {x: x**2 for x in range(1, 1000000)}

Dictionary comprehension is faster because it is optimized internally in Python.


9. When to Use Dictionary Comprehension?

Use dictionary comprehension when:

  • You want a concise and readable way to create dictionaries.
  • You need mapping, filtering, or transforming data.
  • You are working with key-value pairs.

Avoid dictionary comprehension when:

  • The logic is too complex (use loops for clarity).
  • You need to perform multiple operations on values.

Leave a Reply

Your email address will not be published. Required fields are marked *