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.
๐ป Interactive Options:
- ๐ Open in JupyterLite - Full Jupyter environment in your browser
- โถ๏ธ Run code directly below - All code cells on this page are editable and runnable
- ๐ฅ Download Notebook - For use in local Jupyter or Google Colab
๐ 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! ๐ผ