A dictionary maps keys to values — like a real dictionary maps words to definitions. It's the data structure behind JSON, API responses, and most real-world Python.
Create with braces: player = {"name": "Ada", "level": 3}. Read with player["name"] or safely with player.get("coins", 0). Loop pairs with for k, v in player.items():.
player = {"name": "Ada", "level": 3, "alive": True}
print(player["name"]) # Ada
# print(player["coins"]) # KeyError! key doesn't exist
print(player.get("coins")) # None — safe
print(player.get("coins", 0)) # 0 — safe with defaultplayer = {"name": "Ada", "level": 3}
player["coins"] = 100 # add new key
player["level"] += 1 # update existing
player.update({"hp": 50, "mp": 30}) # add/update many
del player["mp"] # delete a key
coins = player.pop("coins") # delete AND get the valuescores = {"ada": 95, "alan": 88, "grace": 92}
for name in scores: # keys by default
print(name)
for name, score in scores.items(): # keys AND values
print(f"{name}: {score}")
best = max(scores, key=scores.get) # key with highest value
print(best) # adaReal data nests. JSON from any API becomes exactly this shape in Python.
users = {
"ada": {"age": 12, "langs": ["python", "scratch"]},
"alan": {"age": 14, "langs": ["python"]},
}
print(users["ada"]["age"]) # 12
print(users["ada"]["langs"][0]) # python
for name, info in users.items():
print(f"{name} knows {len(info['langs'])} language(s)")squares = {n: n * n for n in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# the classic counting pattern:
text = "abracadabra"
counts = {}
for ch in text:
counts[ch] = counts.get(ch, 0) + 1
print(counts) # {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}d["nope"] raises KeyError — use d.get("nope", default) when the key might not existd[(x, y)] = valuefor k in d: raises RuntimeError — loop over list(d) insteadA list is ordered and accessed by position (nums[0]); a dictionary is accessed by key (player["name"]). Use dicts when data has labels.
d.get(key, default) returns the default instead of crashing when the key is missing — [] raises KeyError.
Yes — since Python 3.7 dictionaries preserve insertion order officially.
Yes — values can be anything, including lists and other dictionaries. Keys must be immutable (strings, numbers, tuples).