Dictionaries
Looking values up by key.
6 minute read
Big idea
A dictionary (dict) stores key → value pairs. Instead of looking things up by position, you look them up by name.
Making a dictionary
ages = {"Ada": 36, "Grace": 85, "Linus": 28}
Each entry is key: value. Keys are usually strings or numbers and must be unique; values can be anything.
ages = {"Ada": 36, "Grace": 85}
print(ages["Ada"])
ages["Ada"] = 37
ages["Linus"] = 28
print(ages)
print(len(ages))output
36
{'Ada': 37, 'Grace': 85, 'Linus': 28}
3Run and edit it in the app.
The same syntax, d[key] = value, adds a new key or replaces an existing one's value.
Missing keys
Asking for a key that isn't there is a KeyError. Two safe ways to ask:
stock = {"apple": 5, "pear": 0}
print("banana" in stock)
print(stock.get("banana"))
print(stock.get("banana", 0))
print(stock.get("apple", 0))What does it print? Show the answer
False
None
0
5Run and edit it in the app.
key in d— checks the keys.d.get(key, default)— the value, ordefaultif the key is missing.
Looping
prices = {"tea": 2.5, "cake": 3.0, "soup": 4.75}
for item in prices:
print(item)
for item, price in prices.items():
print(f"{item}: ${price:.2f}")
print(sum(prices.values()))output
tea
cake
soup
tea: $2.50
cake: $3.00
soup: $4.75
10.25Run and edit it in the app.
Looping over a dict gives its keys, in the order they were added. .items() gives (key, value) pairs; .values() gives just the values.
Counting with a dict
A dict makes a perfect tally:
basket = ["apple", "pear", "apple", "fig", "apple"]
counts = {}
for fruit in basket:
counts[fruit] += 1
print(counts)output
{'apple': 3, 'pear': 1, 'fig': 1}Run and edit it in the app.
The first time a fruit appears it isn't a key yet, so counts[fruit] += 1 is a KeyError. Use counts[fruit] = counts.get(fruit, 0) + 1.
Removing
del ages["Linus"] # remove a key (KeyError if missing)
age = ages.pop("Grace") # remove and return its value
d = {'a': 1}. What does d.get('b', 99) return?
Watch it
Think of it like
A real dictionary: you don't read it page by page — you go straight to the word (the key) and read its meaning (the value).
Key terms
- Dictionary (dict) — A collection of key → value pairs.
- Key — The unique name you look up by.
- KeyError — Asking for a key that doesn't exist.
Check yourself
d = {'x': 1}. What does d['x'] = 5 do?
What happens with d['missing'] when the key isn't there?
What does looping for k in d give you?