🌱
Basic
CRUD · Iteration · Comprehension · Set Operations
Week 7 — Dictionaries & Sets
Use dictionaries for key-value storage and sets for unique collections. Learn dict comprehensions, set algebra, and when to choose each structure.
dictsethashcomprehension
Duration
⏱ 2.5 hours
Level
📊 Beginner
Prerequisite
🎯 Week 6
OUTCOME
Build a word frequency counter using dictionaries
What you'll learn
- 1Create, read, update, and delete dictionary entries
- 2Iterate over keys, values, and items
- 3Build dict comprehensions
- 4Perform union, intersection, and difference on sets
- 5Know when to use dict vs list vs set
1. Dictionaries
Dictionaries store key-value pairs. Keys must be unique and hashable (usually strings or numbers).
python
person = {"name": "Alice", "age": 25, "city": "Seoul"}
print(person["name"]) # Alice
person["email"] = "a@ex.com" # add
person["age"] = 26 # update
del person["city"] # delete
print("age" in person) # True
print(person.get("phone", "N/A")) # N/A (safe access)2. Iterating Dictionaries
python
scores = {"Alice": 95, "Bob": 82, "Charlie": 78}
for name in scores: # keys
print(name)
for score in scores.values(): # values
print(score)
for name, score in scores.items(): # both
print(f"{name}: {score}")3. Sets
Sets hold unique, unordered items. Great for membership tests and set algebra.
python
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # union: {1,2,3,4,5,6}
print(a & b) # intersection: {3,4}
print(a - b) # difference: {1,2}
print(a ^ b) # symmetric diff: {1,2,5,6}4. Dict Comprehension
python
# Square each number
squares = {n: n**2 for n in range(1, 6)}
print(squares) # {1:1, 2:4, 3:9, 4:16, 5:25}
# Filter: only even keys
even = {k: v for k, v in squares.items() if k % 2 == 0}
print(even) # {2:4, 4:16}5. Common Mistakes
- dict[key] on a missing key → KeyError. Use dict.get(key, default) for safe access.
- Sets are unordered — don't rely on insertion order. Use a list if order matters.
- {} creates an empty dict, not a set. Use set() for an empty set.
💻 Examples
Run these examples and check the output yourself.
01_phonebook.py— Phone book with CRUD
CODE
phonebook = {}
while True:
cmd = input("add/lookup/delete/quit: ").strip()
if cmd == "add":
name = input(" Name: ")
phone = input(" Phone: ")
phonebook[name] = phone
print(f" Saved {name}.")
elif cmd == "lookup":
name = input(" Name: ")
print(" ", phonebook.get(name, "Not found"))
elif cmd == "delete":
name = input(" Name: ")
phonebook.pop(name, None)
elif cmd == "quit":
break
02_word_count.py— Word frequency counter
CODE
text = input("Enter a sentence: ").lower()
words = text.split()
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
for word, count in sorted(freq.items(), key=lambda x: -x[1]):
print(f" {word}: {count}")
03_set_ops.py— Set algebra on two word lists
CODE
a = set("the cat sat on the mat".split())
b = set("the dog sat on the log".split())
print("Common words: ", a & b)
print("Unique to A: ", a - b)
print("All words: ", a | b)
▶ Output
Common words: {'the', 'on', 'sat'}
Unique to A: {'cat', 'mat'}
All words: {'the', 'on', 'sat', 'cat', 'mat', 'dog', 'log'}📝 Exercises
Try them yourself first, then open the solution to compare.
Exercise 1
Student Grade Book
Goal: Store student names and scores in a dict; print average, highest, and lowest.
Requirements
- Read N students from input
- Store in dict {name: score}
- Print average (2 decimal), top scorer, lowest scorer
▶Toggle solution
SOLUTION
n = int(input("Students: "))
grades = {}
for _ in range(n):
name = input(" Name: ")
score = int(input(" Score: "))
grades[name] = score
avg = sum(grades.values()) / len(grades)
top = max(grades, key=grades.get)
low = min(grades, key=grades.get)
print(f"Average: {avg:.2f}")
print(f"Top: {top} ({grades[top]})")
print(f"Lowest: {low} ({grades[low]})")
Exercise 2
Duplicate Detector
Goal: Find duplicate numbers in a list using a set.
Requirements
- Read space-separated integers
- Use a set to track seen numbers
- Print duplicates in sorted order
Sample I/O
Numbers: 3 5 2 3 7 5 9
Duplicates: [3, 5]▶Toggle solution
SOLUTION
nums = list(map(int, input('Numbers: ').split()))
seen, dups = set(), set()
for n in nums:
if n in seen:
dups.add(n)
seen.add(n)
print('Duplicates:', sorted(dups))
Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub ↗