Unit 4 · Lesson 4
Dictionaries
Dictionaries let you store labeled data — access by meaningful keys instead of position numbers.
Create dictionaries with
{key: value} syntaxAccess, add, and update entries
Use
get() for safe accessCheck for keys with
inDictionaries: Key-Value Pairs
A dictionary maps keys to values — like a real dictionary maps words to definitions:
student = {
"name": "Alex",
"age": 16,
"grade": 95
}
print(student["name"]) # "Alex"
student["grade"] = 98 # Update
student["email"] = "alex@school.com" # Add new key
Safe Access with get()
# student["phone"] would crash with KeyError!
phone = student.get("phone", "N/A") # Returns "N/A" if missing
# Check if key exists:
if "email" in student:
print("Has email!")
Lists vs Dicts: Lists access by position (index 0, 1, 2...). Dicts access by key (any string or number). Use lists for ordered sequences, dicts for labeled data.
Practice Time
Challenges
Challenge 1: Contact Book
Guided
Store contacts as name→phone pairs in a dictionary.
Instructions: Create
contacts with 3 name→phone entries. Look up "Alice"'s number and store in alice_phone. Add a new contact "Diana" with number "555-4444". Store total contacts in total.Hint:
alice_phone = contacts["Alice"], contacts["Diana"] = "555-4444", total = len(contacts)Challenge 2: Word Counter
Guided
Count occurrences of each word in a sentence.
Instructions: Split
sentence into words and count how many times each appears. Store in word_counts dict.Hint:
for word in words: then if word in word_counts: word_counts[word] += 1 else word_counts[word] = 1Challenge 3: Inventory System
Solo
Track item quantities in a store inventory.
Instructions: Given
inventory dict, add 5 to "apples" stock, reduce "bananas" by 2, add new item "grapes" with 15. Store total stock (sum of all values) in total_stock.Hint 1:
Hint 2:
inventory["apples"] += 5Hint 2:
for item in inventory: total_stock += inventory[item]Challenge 4: Emoji Translator
Stretch
Map words to emoji and translate a sentence.
Instructions: Given an
emoji_map dict and a sentence, replace any words that have an emoji mapping. Store result in translated.Hint: Split sentence into words. For each word, use
emoji_map.get(word, word) — returns the emoji if found, otherwise the original word. Join with spaces.