Quest 7: Dictionaries - The Key Keeper
Store Data in Key-Value Pairs
🗝️ QUEST 7 | Difficulty: Intermediate | Time: 5 minutes
📊 Complexity Level: Intermediate ⭐⭐
Builds on fundamental concepts from earlier quests. Best for students who have completed Quests 1-6 or have some basic programming experience. This introduces more advanced data structures.
📖 Introduction: The Magic Phonebook
You’re keeping track of your friends’ phone numbers. With a list, you’d have:
names = ["Alice", "Bob", "Charlie"]
phones = ["555-1234", "555-5678", "555-9012"]
# Which number belongs to who? Confusing!What if you could look up numbers by name, like a phonebook? That’s what dictionaries do! They store data in key-value pairs.
🗃️ Story Time: You’ve discovered a magical filing cabinet. Instead of folders numbered 0, 1, 2 (like lists), each folder has a label: “Health Potions”, “Gold Coins”, “Magic Spells”. You can instantly find what you need by its name, not by remembering its position!
💡 Explanation: What are Dictionaries?
A dictionary stores data as key-value pairs: - Key: The label (like “name” or “health”) - Value: The data (like “Hero” or 100)
# Creating dictionaries
player = {
"name": "Hero",
"level": 5,
"health": 100,
"inventory": ["sword", "shield"]
}
# Access values by key
print(player["name"]) # "Hero"
print(player["level"]) # 5🎯 Dictionary vs List:
List: Ordered, accessed by numeric index
items = ["sword", "shield", "potion"]
print(items[0]) # "sword"Dictionary: Key-value pairs, accessed by key
stats = {"strength": 10, "speed": 15}
print(stats["strength"]) # 10When to use what? - List: When order matters, or you have simple collections - Dictionary: When you need to look up values by name/label
🎮 Activity: Character Stats
Create and manage a character using a dictionary:
🎯 Challenge:
- Create a dictionary for a wizard character with different stats
- Give the wizard high intelligence (30) but low strength (5)
- Add a “spells” key with a list of spell names
- Print the wizard’s info in a nice format
👨💻 Code Example: Inventory System
Dictionaries are perfect for managing game inventories:
💡 Dictionary Methods:
dict.keys()- Get all keysdict.values()- Get all valuesdict.items()- Get all key-value pairsdict.get(key, default)- Safely get value (returns default if key doesn’t exist)dict.pop(key)- Remove and return valuedict.update(other_dict)- Merge dictionaries
stats = {"hp": 100, "mp": 50}
print(stats.keys()) # dict_keys(['hp', 'mp'])
print(stats.values()) # dict_values([100, 50])
print(stats.get("hp", 0)) # 100
print(stats.get("xp", 0)) # 0 (default since "xp" doesn't exist)🧩 Puzzle Time!
What will this code create? Predict the output:
🔑 Solution Explained:
The output is:
Scores Dictionary:
level_1: 150
level_2: 150
total: 300
Step-by-step trace:
Start with empty dictionary:
{}Add
level_1:{"level_1": 100}Add
level_2:{"level_1": 100, "level_2": 150}Update
level_1to 100 + 50 = 150:{"level_1": 150, "level_2": 150}Add
total= 150 + 150 = 300:{"level_1": 150, "level_2": 150, "total": 300}
Key insight: When you assign to an existing key (like scores["level_1"]), it updates the value instead of creating a duplicate key. Dictionary keys are unique!
🎮 Bonus: Nested Dictionaries
Dictionaries can contain other dictionaries for complex data:
🎯 Key Takeaways
✨ Quest 7 Complete! ✨
You’ve learned:
✅ Dictionaries store key-value pairs
✅ Access values using keys: dict[key]
✅ Keys must be unique; values can be any type
✅ Use .items(), .keys(), .values() to iterate
✅ Dictionaries can be nested for complex data
✅ Use .get() for safe access with defaults
Next Quest: Ready for beautiful patterns? Try Quest 8: Fibonacci!
🚀 Try This at Home!
Create a contacts app:
contacts = {
"Alice": {"phone": "555-1234", "email": "[email protected]"},
"Bob": {"phone": "555-5678", "email": "[email protected]"},
"Charlie": {"phone": "555-9012", "email": "[email protected]"}
}
# Look up a contact
name = "Alice"
if name in contacts:
print(f"{name}'s phone: {contacts[name]['phone']}")Or a simple game state manager:
game_state = {
"current_level": 1,
"player": {
"health": 100,
"position": {"x": 0, "y": 0}
},
"enemies": {
"goblin_1": {"health": 30, "position": {"x": 10, "y": 5}},
"goblin_2": {"health": 30, "position": {"x": 15, "y": 8}}
}
}
print(f"Level: {game_state['current_level']}")
print(f"Player health: {game_state['player']['health']}")📱 Outstanding! Dictionaries are everywhere in real programs. You’re becoming a pro! 💼