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()).
Build a dictionary describing a hero or pet: name, age, power, and anything else. Look up values, change them, and print the result. Make it yours!
๐๏ธ Extra Practice โ Drill Time!
Dictionaries are how real apps remember things โ players, settings, scores, inventories. Time to build a lot of them.
๐
Task 6: Safe Look-Up with get
Easy
With hero = {"name": "Zara", "level": 7}: print the name, then try hero.get("pet") for a key that does not exist, then hero.get("pet", "none yet") which gives a backup answer instead of crashing.
With prices = {"apple": 2, "pear": 3, "plum": 1}, loop three times: first print every key, then every value, then print each pair as apple costs 2 using .items().
apple
pear
plum
2
3
1
apple costs 2
pear costs 3
plum costs 1
prices = {"apple": 2, "pear": 3, "plum": 1}
for key in prices:
print(key)
for value in prices.values():
print(value)
for fruit, price in prices.items():
print(f"{fruit} costs {price}")
โ๏ธ
Task 8: Change and Delete
Easy
Start with settings = {"sound": True, "level": 1, "cheats": True}. Turn the sound off, raise the level to 2, add "nickname": "Ace", delete the cheats key with del, then print the dictionary.
With stock = {"pens": 4, "books": 0}: print Yes if "pens" is a key (use in), and print Not sold here if "rulers" is not a key.
Yes
Not sold here
stock = {"pens": 4, "books": 0}
if "pens" in stock:
print("Yes")
if "rulers" not in stock:
print("Not sold here")
๐ค
Task 10: Letter Counter
Tricky
Count how many times each letter appears in word = "banana" using a dictionary, then print the dictionary. Hint: for each letter, counts[letter] = counts.get(letter, 0) + 1.
{'b': 1, 'a': 3, 'n': 2}
word = "banana"
counts = {}
for letter in word:
counts[letter] = counts.get(letter, 0) + 1
print(counts)
๐งฎ
Task 11: Totals and Winners
Medium
With scores = {"Ana": 42, "Ben": 91, "Cy": 67}, print the total of all scores, the highest score, and the name of the winner. Hint for the winner: max(scores, key=scores.get).
Build team holding two players, each with their own dictionary of level and hp. Print the level of the first player, then loop through and print Ana is level 3 with 50 hp style lines for everyone.
3
Ana is level 3 with 50 hp
Ben is level 5 with 80 hp
team = {
"Ana": {"level": 3, "hp": 50},
"Ben": {"level": 5, "hp": 80},
}
print(team["Ana"]["level"])
for name, info in team.items():
print(f"{name} is level {info['level']} with {info['hp']} hp")
๐
Task 13: Two Lists Into One Dictionary
Tricky
You have countries = ["France", "Japan", "Peru"] and capitals = ["Paris", "Tokyo", "Lima"]. Build a dictionary that maps each country to its capital and print it. Hint: dict(zip(a, b)).
A shop has prices = {"apple": 2, "bread": 3, "milk": 4} and a customer's cart = ["apple", "milk", "apple", "bread"]. Print one line per different item like apple x2 = 4 (in the order apple, bread, milk), then a final TOTAL = 11.
apple x2 = 4
bread x1 = 3
milk x1 = 4
TOTAL = 11
prices = {"apple": 2, "bread": 3, "milk": 4}
cart = ["apple", "milk", "apple", "bread"]
counts = {}
for item in cart:
counts[item] = counts.get(item, 0) + 1
total = 0
for item in sorted(counts):
cost = counts[item] * prices[item]
total += cost
print(f"{item} x{counts[item]} = {cost}")
print(f"TOTAL = {total}")
๐พ
Task 15: Free Play โ Your Own Database
Creative
Build a dictionary about something you love: pokรฉmon stats, planet facts, your class timetable. Add at least five entries, print them nicely with a loop, then look one up and change one. ๐