intermediate
Dict & Set Comprehensions
5 min read
Overview
Just like list comprehensions, Dictionary and Set Comprehensions provide a clean one-line syntax to build dictionaries and sets dynamically from iterables.
Learning Objectives
- Use
{key_expr: val_expr for item in iterable}to build dictionaries. - Use
{expr for item in iterable}to build unique sets. - Filter key-value pairs using conditional logic.
Concept Explanation
- Dictionary Comprehension Syntax:
python
new_dict = {key_func(item): val_func(item) for item in iterable if condition} - Set Comprehension Syntax:
python
new_set = {func(item) for item in iterable if condition}
Code Examples
Example 1 — Dictionary Comprehension
python
names = ["Alice", "Bob", "Charlie"]
# Create a dictionary mapping name -> length
name_lengths = {name: len(name) for name in names}
print("Name Lengths:", name_lengths) # {'Alice': 5, 'Bob': 3, 'Charlie': 7}
# Swapping keys and values in a dictionary
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print("Inverted Dict:", inverted) # {1: 'a', 2: 'b', 3: 'c'}
Example 2 — Set Comprehension
python
words = ["apple", "BANANA", "cherry", "APPLE", "banana"]
# Extract unique lowercase word lengths
unique_word_lengths = {len(w) for w in words}
print("Unique Word Lengths:", unique_word_lengths) # {5, 6}
# Extract unique uppercase words
clean_words = {w.upper() for w in words}
print("Unique Words:", clean_words)
Common Mistakes
- Overwriting Duplicate Keys in Dict Comprehensions: If the key expression produces identical keys for different items, later items overwrite earlier ones.
Best Practices
- Use dict comprehensions to transpose or filter configuration mappings.
- Use set comprehensions when transforming data that requires uniqueness guarantees.