Dict & Set Comprehensions
Just like list comprehensions, Python also lets you create dictionaries and sets in one line. Plus, there are two super useful tools: enumerate() and zip().
1. Dictionary Comprehension
Formula:
new_dict = {key: value for item in iterable}
Examples:
# Create a dict of squares: {1: 1, 2: 4, 3: 9, ...}
squares = {n: n ** 2 for n in range(1, 6)}
print(squares)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Create a dict from two lists
names = ["sai", "ravi", "priya"]
scores = [85, 72, 91]
student_scores = {name: score for name, score in zip(names, scores)}
print(student_scores)
# Output: {'sai': 85, 'ravi': 72, 'priya': 91}
# Filter: Only students who scored above 80
toppers = {name: score for name, score in zip(names, scores) if score > 80}
print(toppers)
# Output: {'sai': 85, 'priya': 91}
2. Set Comprehension
A set comprehension is the same idea, but it creates a set (no duplicates, no order).
Formula:
new_set = {expression for item in iterable}
Examples:
# Get unique first letters from a list of names
names = ["sai", "ravi", "priya", "suman", "ramesh"]
first_letters = {name[0] for name in names}
print(first_letters)
# Output: {'s', 'r', 'p'} (no duplicates, order may vary)
# Get all unique word lengths
words = ["python", "ai", "ml", "data", "ai"]
unique_lengths = {len(word) for word in words}
print(unique_lengths)
# Output: {6, 2, 4}
3. enumerate() — Get Index + Value Together
When you loop through a list, sometimes you need both the position (index) and the value. Instead of creating a counter variable yourself, use enumerate():
fruits = ["apple", "banana", "cherry"]
# Without enumerate (the hard way)
i = 0
for fruit in fruits:
print(i, fruit)
i += 1
# With enumerate (the easy way)
for index, fruit in enumerate(fruits):
print(index, fruit)
# Output:
# 0 apple
# 1 banana
# 2 cherry
Starting from a Different Number:
for rank, fruit in enumerate(fruits, start=1):
print(f"#{rank}: {fruit}")
# Output:
# #1: apple
# #2: banana
# #3: cherry
Using enumerate in a Comprehension:
# Create a numbered dict
numbered = {i: fruit for i, fruit in enumerate(fruits, start=1)}
print(numbered)
# Output: {1: 'apple', 2: 'banana', 3: 'cherry'}
4. zip() — Combine Two Lists Together
zip() takes two (or more) lists and pairs their items together one by one:
names = ["Sai", "Ravi", "Priya"]
scores = [85, 72, 91]
# Pair them together
for name, score in zip(names, scores):
print(f"{name} scored {score}")
# Output:
# Sai scored 85
# Ravi scored 72
# Priya scored 91
Using zip in a Comprehension:
# Create a list of formatted strings
results = [f"{name}: {score}" for name, score in zip(names, scores)]
print(results)
# Output: ['Sai: 85', 'Ravi: 72', 'Priya: 91']
Important: If the lists have different lengths,
zip()stops at the shortest list.
5. Why This Matters for AI & ML
These tools are used everywhere in real AI code:
# Pair feature names with their values
features = ["temperature", "humidity", "wind_speed"]
values = [32.5, 78.0, 12.3]
feature_dict = {name: val for name, val in zip(features, values)}
print(feature_dict)
# Output: {'temperature': 32.5, 'humidity': 78.0, 'wind_speed': 12.3}
# Number your training data
data = ["image1.jpg", "image2.jpg", "image3.jpg"]
labeled = {idx: img for idx, img in enumerate(data)}
print(labeled)
# Output: {0: 'image1.jpg', 1: 'image2.jpg', 2: 'image3.jpg'}
Quick Summary
- Dict Comprehension:
{key_expr: value_expr for item in iterable}creates mappings dynamically in one line. - Set Comprehension:
{expr for item in iterable}creates deduplicated sets in one line. enumerate(iterable): Yields(index, item)pairs simultaneously during iteration.zip(list1, list2): Combines corresponding items from multiple sequences in lockstep.
What's Next?
Let's explore essential idiomatic shortcuts and clean-code techniques in Pythonic Patterns in the next lesson!