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"])  # 10

When 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:

  1. Create a dictionary for a wizard character with different stats
  2. Give the wizard high intelligence (30) but low strength (5)
  3. Add a “spells” key with a list of spell names
  4. 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 keys
  • dict.values() - Get all values
  • dict.items() - Get all key-value pairs
  • dict.get(key, default) - Safely get value (returns default if key doesn’t exist)
  • dict.pop(key) - Remove and return value
  • dict.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:

  1. Start with empty dictionary: {}

  2. Add level_1: {"level_1": 100}

  3. Add level_2: {"level_1": 100, "level_2": 150}

  4. Update level_1 to 100 + 50 = 150: {"level_1": 150, "level_2": 150}

  5. 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! 💼