Dictionary & Set Comprehensions
Create dictionaries and sets efficiently using comprehensions
Dictionary & Set Comprehensions
Dictionary Comprehensions
Just like list comprehensions, dictionary comprehensions let you create dictionaries in one line. The difference is you need both a key and value.
Basic Pattern
new_dict = {key: value for item in sequence}Simple Example
Old way with loop:
numbers = [1, 2, 3, 4]
squares = {}
for n in numbers:
squares[n] = n * n
print(squares)Result: {1: 1, 2: 4, 3: 9, 4: 16}
New way with comprehension:
numbers = [1, 2, 3, 4]
squares = {n: n * n for n in numbers}
print(squares)Result: {1: 1, 2: 4, 3: 9, 4: 16}
How to read it: "Create a dictionary where key is n and value is n times n, for each n in numbers"
Creating Dictionaries from Lists
Names and Ages
names = ["John", "Sarah", "Mike"]
ages = [25, 30, 28]
people = {name: age for name, age in zip(names, ages)}
print(people)Result: {'John': 25, 'Sarah': 30, 'Mike': 28}
What happens: zip() pairs up names with ages, then comprehension creates key-value pairs.
String Lengths
words = ["apple", "banana", "kiwi"]
lengths = {word: len(word) for word in words}
print(lengths)Result: {'apple': 5, 'banana': 6, 'kiwi': 4}
Adding Conditions to Dictionary Comprehensions
You can filter which items to include.
numbers = [1, 2, 3, 4, 5, 6]
even_squares = {n: n * n for n in numbers if n % 2 == 0}
print(even_squares)Result: {2: 4, 4: 16, 6: 36}
What this does: Only creates entries for even numbers.
Filtering by Value
prices = {"apple": 1.5, "banana": 0.8, "orange": 2.0, "kiwi": 3.5}
expensive = {item: price for item, price in prices.items() if price > 1.5}
print(expensive)Result: {'orange': 2.0, 'kiwi': 3.5}
Transforming Existing Dictionaries
Swapping Keys and Values
original = {"a": 1, "b": 2, "c": 3}
swapped = {value: key for key, value in original.items()}
print(swapped)Result: {1: 'a', 2: 'b', 3: 'c'}
What happens: Values become keys, keys become values.
Modifying Values
prices = {"apple": 1.0, "banana": 0.5, "orange": 1.5}
discounted = {item: price * 0.9 for item, price in prices.items()}
print(discounted)Result: {'apple': 0.9, 'banana': 0.45, 'orange': 1.35}
What this does: Applies 10 percent discount to all prices.
Uppercase Keys
data = {"name": "John", "age": 25, "city": "NYC"}
upper = {key.upper(): value for key, value in data.items()}
print(upper)Result: {'NAME': 'John', 'AGE': 25, 'CITY': 'NYC'}
Nested Dictionary Comprehensions
You can create nested dictionaries using comprehensions.
students = ["John", "Sarah", "Mike"]
subjects = ["Math", "Science"]
grades = {student: {subject: 0 for subject in subjects} for student in students}
print(grades)Result: {'John': {'Math': 0, 'Science': 0}, 'Sarah': {'Math': 0, 'Science': 0}, 'Mike': {'Math': 0, 'Science': 0}}
What this creates: Each student gets a dictionary with all subjects initialized to 0.
Set Comprehensions
Set comprehensions work like list comprehensions but create sets (unique values only).
Basic Pattern
new_set = {expression for item in sequence}Simple Example
numbers = [1, 2, 2, 3, 3, 3, 4]
squares = {n * n for n in numbers}
print(squares)Result: {1, 4, 9, 16}
What happens: Squares all numbers and automatically removes duplicates.
Extracting Unique Items
text = "hello world"
unique_letters = {char for char in text if char.isalpha()}
print(unique_letters)Result: {'h', 'e', 'l', 'o', 'w', 'r', 'd'}
Notice: Each letter appears only once, even though "l" appears twice in "hello".
Set Comprehensions with Conditions
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = {n for n in numbers if n % 2 == 0}
print(even_numbers)Result: {2, 4, 6, 8}
Multiple Conditions
numbers = range(20)
filtered = {n for n in numbers if n % 2 == 0 and n > 5}
print(filtered)Result: {6, 8, 10, 12, 14, 16, 18}
What this does: Only includes numbers that are even AND greater than 5.
Practice Example
The scenario: You're analyzing product inventory and customer orders.
products = ["laptop", "phone", "tablet", "mouse", "keyboard"]
prices = [999, 599, 399, 25, 75]
inventory = {product: price for product, price in zip(products, prices)}
print("Inventory:", inventory)
expensive = {p: pr for p, pr in inventory.items() if pr >= 100}
print("Expensive items:", expensive)
discounted = {p: pr * 0.8 for p, pr in inventory.items()}
print("Sale prices:", discounted)
orders = ["laptop", "mouse", "laptop", "phone", "mouse", "tablet"]
unique_orders = {item for item in orders}
print("Unique products ordered:", unique_orders)
order_counts = {item: orders.count(item) for item in unique_orders}
print("Order counts:", order_counts)
categories = {
product: "Accessory" if price < 100 else "Device"
for product, price in inventory.items()
}
print("Categories:", categories)What this program does:
- Creates inventory dictionary from two lists
- Filters expensive items (100 or more)
- Applies 20 percent discount to all prices
- Creates set of unique ordered products
- Counts how many times each product was ordered
- Categorizes products based on price
Key Points to Remember
Dictionary comprehension format is {key: value for item in sequence}. You must specify both key and value separated by colon.
Set comprehension format is {expression for item in sequence}. Uses curly braces like dict but no colon, automatically removes duplicates.
Add "if condition" at the end to filter items for both dictionary and set comprehensions.
You can transform existing dictionaries by iterating over items() and modifying keys, values, or both.
Set comprehensions are perfect for extracting unique values from lists or strings.
Common Mistakes
Mistake 1: Forgetting colon in dictionary comprehension
nums = [1, 2, 3]
squares = {n * n for n in nums} # This creates set, not dict!
squares = {n: n * n for n in nums} # Correct dictionaryMistake 2: Creating empty set with {}
empty = {} # This is dictionary!
empty = set() # Correct empty setMistake 3: Too complex nested comprehension
result = {x: {y: x * y for y in range(5) if y != x} for x in range(5) if x > 0}This is hard to read. Break it into multiple steps or use regular loops.
Mistake 4: Duplicate keys in dictionary comprehension
numbers = [1, 2, 2, 3, 3]
squares = {n: n * n for n in numbers}Result: {1: 1, 2: 4, 3: 9}
Duplicates are overwritten. Last value wins for each key.
What's Next?
You now know how to create lists, dictionaries, and sets using comprehensions. Next, you'll learn about working with files - reading data from files and writing data to files.