Dictionaries
Intermediate · 20 min read · ▶ live playground · ✦ checkpoint
A list asks, "What is at position 2?" A dictionary asks a more human question: "What is Mina's score?" A dictionary is a mutable collection of key-value pairs, meaning each key is a label you search with and each value is the data stored under that label.
A dictionary stores labeled values
Think of a dictionary as labeled cubbies. You do not count across the row to cubby 0, 1, or 2; you ask for the cubby labeled "score" and take out the value inside.
A dictionary literal is a dictionary written directly in code with curly braces. Each key sits before :, and its value sits after :.
player = {
"name": "Mina",
"score": 42,
"mood": "focused",
}
print(player["name"])
print(player["score"])
print(f"{player['name']} feels {player['mood']}.")Mina42Mina feels focused.
Read player["score"] as "from player, get the value under the key "score"." That square-bracket form is a confident lookup: you expect the key to exist.
Keys are usually strings in beginner code because strings make great labels: "name", "score", "mood". Values can be strings, numbers, Booleans, lists, other dictionaries, and more. One key appears only once in a dictionary; if you need several scores, store them under different keys or use a list as the value.
Add, update, and delete by key
Dictionaries are mutable, so you can change the same dictionary object in place. Assignment with a new key adds a pair. Assignment with an existing key updates that pair. del removes a pair.
snack_counts = {"apples": 3, "mangoes": 1}
snack_counts["bananas"] = 5
snack_counts["apples"] = snack_counts["apples"] + 2
del snack_counts["mangoes"]
print(snack_counts)
print("apples:", snack_counts["apples"]){'apples': 5, 'bananas': 5}apples: 5
The name snack_counts still points at the same dictionary. The labeled cubbies changed: one new cubby, one updated cubby, one removed cubby.
If you use brackets with a missing key, Python raises a KeyError, an error that means "this dictionary does not have that key"; full exception handling comes in lesson 9.3. When a missing key is normal, use get().
Use get and setdefault for missing keys
get() looks up a key without crashing when the key is missing. A default is a fallback value Python uses when the real value is missing.
inventory = {"apples": 5, "bananas": 2}
print(inventory.get("apples"))
print(inventory.get("oranges"))
print(inventory.get("oranges", 0))
inventory.setdefault("oranges", 0)
inventory.setdefault("apples", 99)
print(inventory)5None0{'apples': 5, 'bananas': 2, 'oranges': 0}
inventory.get("oranges") returns None because the key is missing and you did not give a default. inventory.get("oranges", 0) returns 0 instead.
setdefault(key, value) is more active. If the key is missing, it adds that key with the default value. If the key already exists, it leaves the old value alone. That is why "oranges" appears with 0, but "apples" stays 5, not 99.
Loop through keys, values, and items
A direct loop over a dictionary steps through its keys. The methods keys(), values(), and items() make your intent clearer: labels only, stored values only, or full pairs.
scores = {"Mina": 42, "Ravi": 35, "Noor": 39}
print("Keys")
for player in scores.keys():
print(player)
print("Values")
for score in scores.values():
print(score)
print("Items")
for player, score in scores.items():
print(f"{player}: {score}")KeysMinaRaviNoorValues423539ItemsMina: 42Ravi: 35Noor: 39
items() gives one key-value pair at a time. Because each pair has two parts, the loop can unpack it into player and score, just like tuple unpacking from lesson 5.2.
Python keeps dictionary keys in the order you added them. Still, choose a dictionary because labels matter, not because positions matter. When positions are the main idea, a list is usually clearer.
Try it - update a scoreboard
Change a score, add another player, and try a missing player name at the bottom. Notice which lookups change the dictionary and which ones only read from it.
Dictionary comprehensions build dictionaries
A dictionary comprehension is a compact expression that builds a new dictionary by looping over another collection. It looks like a list comprehension, but the first part has key: value.
names = ["Mina", "Jo", "Noor"]
score_by_player = {name: len(name) * 10 for name in names}
passing_scores = {
name: score
for name, score in score_by_player.items()
if score >= 40
}
print(score_by_player)
print(passing_scores){'Mina': 40, 'Jo': 20, 'Noor': 40}{'Mina': 40, 'Noor': 40}
Read the first comprehension as "for each name in names, store the key name with the value len(name) * 10."
The second comprehension loops through score_by_player.items(), unpacks each pair, and keeps only scores at least 40. Use a normal loop when the work takes several steps. Use a comprehension when the whole idea fits in one calm line or a small, readable block.
Nested dictionaries model records
A nested dictionary is a dictionary stored inside another dictionary. This lets one record hold smaller labeled records inside it.
profile = {
"player": "Mina",
"stats": {
"score": 42,
"level": 3,
},
"badges": ["helper", "fast finisher"],
}
print(profile["player"])
print(profile["stats"]["score"])
profile["stats"]["score"] = profile["stats"]["score"] + 8
profile["badges"].append("comeback")
print(profile)Mina42{'player': 'Mina', 'stats': {'score': 50, 'level': 3}, 'badges': ['helper', 'fast finisher', 'comeback']}
Read profile["stats"]["score"] from left to right. First get the "stats" dictionary. Then, inside that dictionary, get "score".
This shape is common in JSON-like data, nested dictionaries and lists shaped like data you might later save to a file or send between programs; formal JSON files and parsing come in lesson 9.2. For now, focus on the shape: dictionaries are good for labels, lists are good for ordered groups, and nesting lets you combine both.
Checkpoint
Answer all three to mark this lesson complete
Dictionaries let your code find values by meaning instead of position. Next, sets give you a collection for uniqueness: one copy of each value, plus useful math for comparing groups.