A dictionary stores pairs: a key and its value. Instead of looking things up by position like a list, you look them up by name, like a real dictionary or a contact list.
MAKING A DICTIONARY
hero = {"name": "Ana", "hp": 30, "level": 2}
print(hero["name"])
print(hero["hp"])Ana
30
Curly brackets, each pair written as key: value, pairs separated by commas.
ADDING AND CHANGING VALUES
hero = {"name": "Ana", "hp": 30}
hero["hp"] = 25
hero["weapon"] = "bow"
print(hero){'name': 'Ana', 'hp': 25, 'weapon': 'bow'}
If the key exists, its value is replaced. If it doesn't, a new pair is added.
SAFE LOOKUPS WITH GET()
prices = {"apple": 2, "cake": 5}
print(prices.get("cake"))
print(prices.get("pizza", 0))5
0
prices["pizza"] would crash with a KeyError. get() returns a default value instead.
LOOPING OVER A DICTIONARY
inventory = {"potion": 3, "arrow": 12}
for item, count in inventory.items():
print(item, "x", count)potion x 3
arrow x 12
COUNTING THINGS (A CLASSIC)
counts = {}
for word in ["cat", "dog", "cat", "cat"]:
counts[word] = counts.get(word, 0) + 1
print(counts){'cat': 3, 'dog': 1}
stock = {"apple": 4, "pear": 2}
stock["apple"] += 1
print(stock["apple"] + stock["pear"])WHEN TO USE A LIST VS A DICTIONARY
- List: things in order, found by position (the top 10 scores).
- Dictionary: things found by name (a player's settings, prices by product).
COMMON BEGINNER MISTAKES
if key in d: or use get().d[0] to give the first item. Dictionaries are looked up by key, not by position.d = {"a": 1, "b": 2}
d["a"] = d["b"] * 10
print(len(d), d["a"])d["a"] becomes 2 × 10 = 20.PRACTICE IT, DON'T JUST READ IT
In Dict Dungeon you build an inventory system with dictionaries, one swipe-sized step at a time.
PLAY DICT DUNGEON ▸FAQ
What is a dictionary in Python?
A collection of key: value pairs, like {"name": "Ana", "hp": 30}. You look up values by their key.
How do I avoid a KeyError?
Check with if key in d first, or use d.get(key, default), which returns the default instead of crashing.
Can a dictionary have two equal keys?
No. Each key is unique; setting it again replaces the old value.