A dictionary stores pairs of keys and values. Instead of looking things up by position (like a list), you look them up by a name (the key). Just like a real dictionary: you look up a word (key) to find its meaning (value).
player = {
"name": "Maya",
"level": 7,
"health": 100
}
Curly braces { }, and each pair is written as key: value.
player["level"] = 8 # change a value
player["score"] = 250 # add a brand-new pair
print(player)
🔍 Safe lookups with .get()
Missing keys cause errors
Asking for a key that doesn't exist (player["age"]) crashes the program. Use .get() to avoid that — it returns None (or a default) instead.
print(player.get("age")) # None (no crash)
print(player.get("age", "unknown")) # unknown
🔁 Looping through a dictionary
prices = {"apple": 2, "banana": 1, "cherry": 5}
for fruit in prices:
print(f"{fruit} costs ${prices[fruit]}")
# Or get both at once with .items()
for fruit, price in prices.items():
print(f"{fruit}: {price}")
🛠️ Useful tools
prices = {"apple": 2, "banana": 1}
print(prices.keys()) # the keys
print(prices.values()) # the values
print("apple" in prices) # True — is this key there?
print(len(prices)) # 2 — how many pairs
✅ What you learned
Dictionaries store key → value pairs in { }.
Look up with dict["key"] or safely with .get().
Add or change with dict["key"] = value.
Loop with for k in dict or .items().
🎮 Time to Practice!
Build little databases of your own. 🗂️
🐕
Task 1: Look It Up
Easy
A dictionary dog = {"name": "Rex", "age": 4}. Print just the dog's name. Expected: Rex
dog = {"name": "Rex", "age": 4}
print(dog["name"])
🍎
Task 2: Fruit Inventory
Medium
A dictionary stock = {"apple": 3, "banana": 5}. Loop with .items() and print each line as fruit: count.
stock = {"apple": 3, "banana": 5}
for fruit, count in stock.items():
print(f"{fruit}: {count}")
🎮
Task 3: New Player
Medium
Start with player = {"name": "Zoe", "level": 1}. Add a new key "xp" with value 0, then print the whole dictionary. Expected: {'name': 'Zoe', 'level': 1, 'xp': 0}
player = {"name": "Zoe", "level": 1}
player["xp"] = 0
print(player)
🧮
Task 4: Add Up the Values
Tricky
A dictionary basket = {"apple": 3, "pear": 5}. Print the total number of fruits: Total: 8. Hint: sum(basket.values()).