Dictionaries
Look things up by name, not position
In this lesson
A dictionary stores pairs: a key and the value it points to. Instead of looking things up by position like a list, you look them up by a meaningful name. It’s perfect for ‘this goes with that’ data.
Explain it like I’m 5
A dictionary is like a real dictionary: you look up a word (the key) and get its meaning (the value). You don’t care what page it’s on — you find it by the word itself.
Keys and values
Write a dictionary with curly braces and key: value pairs: ages = {"Ada": 36, "Linus": 54}. You read a value by its key: ages["Ada"] gives 36. Keys are usually strings or numbers and must be unique; values can be anything. There’s no index — the key is how you find things.
ages = {"Ada": 36, "Linus": 54}
print(ages["Ada"])
print(ages["Linus"])
36 54
Adding, updating, and removing
Assigning to a new key adds it: ages["Grace"] = 41. Assigning to an existing key updates it: ages["Ada"] = 37. del ages["Linus"] removes a pair. Because each key is unique, writing to a key either creates or overwrites — there are never duplicates.
stock = {"apples": 12, "pears": 5}
stock["bananas"] = 8 # add a new key
stock["apples"] = 9 # update an existing key
del stock["pears"] # remove a key
print(stock)
{'apples': 9, 'bananas': 8}
Safe access with .get()
Asking for a missing key with ages["Bob"] raises a KeyError and stops your program. ages.get("Bob") returns None instead, and ages.get("Bob", 0) returns a default of your choice. Use .get() whenever a key might be absent. The in operator also tests presence: "Ada" in ages.
prices = {"coffee": 3, "tea": 2}
print(prices.get("coffee", 0))
print(prices.get("juice", 0))
3 0
Count how many times each letter appears in the word. Run it to see the tally for 'banana'.
word = "banana"
counts = {}
for letter in word:
counts[letter] = counts.get(letter, 0) + 1
print(counts)
counts.get(letter, 0) returns the current count or 0 if the letter is new, and adding 1 stores the updated tally.
word = "banana"
counts = {}
for letter in word:
counts[letter] = counts.get(letter, 0) + 1
print(counts)
{'b': 1, 'a': 3, 'n': 2}
Looping over a dictionary
Looping over a dict gives its keys: for name in ages:. To get keys and values together, use .items(): for name, age in ages.items():. There’s also .keys() and .values(). When to use a dict vs a list: a list is for ordered items you reach by position; a dict is for looking things up by a name or id.
scores = {"Ada": 90, "Bo": 75, "Cy": 88}
for name, score in scores.items():
print(name, "scored", score)
Ada scored 90 Bo scored 75 Cy scored 88
Nested dictionaries and setdefault()
A dictionary’s values can themselves be dictionaries, which is how you model structured records — each person with their own age, city, and so on under one key. You reach in with repeated keys: people["ada"]["city"].
.setdefault(key, default) reads a key but inserts a default first if it’s missing — a tidy way to build up groups without checking ‘does this key exist yet?’ every time. (Structured data like this is commonly saved as JSON, which the standard library’s json module handles — learn more about modules here.)
people = {
"ada": {"age": 36, "city": "London"},
"bo": {"age": 41, "city": "Oslo"},
}
print(people["ada"]["city"])
groups = {}
groups.setdefault("python", []).append("ada")
groups.setdefault("python", []).append("bo")
print(groups)
London
{'python': ['ada', 'bo']}
Common mistake: KeyError when a key doesn't exist
Accessing d["missing"] raises a KeyError because there’s no such key.
Check with if key in d: or use d.get(key, default) to supply a fallback value instead of crashing.
How do you read a value from a dictionary?
Dictionaries are keyed by name, not position — you look values up by their key.
What does d.get("x", 0) do when "x" is missing?
.get() returns the default instead of raising an error, and does not modify the dictionary.
Mini exercise (medium)
Given a list of words ["red", "blue", "red", "green", "blue", "red"], build a dictionary mapping each word to how many times it appears, then print it.
Do it here. Finish the code below and press Run to try your answer right in the browser — no setup needed.
words = ["red", "blue", "red", "green", "blue", "red"]
counts = {}
for word in words:
# TODO: add 1 to this word’s count
pass
print(counts)
Loop over the words and use counts[word] = counts.get(word, 0) + 1.
words = ["red", "blue", "red", "green", "blue", "red"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
assert counts == {"red": 3, "blue": 2, "green": 1}, "counts should map red to 3, blue to 2, green to 1"
print("✓ Counted!")