Explain it simply
Explain it simply
Think of a real dictionary book. You look up a word (the key) and find its meaning (the value) straight away, without remembering a page number. A Python dictionary works the same way: ask for person["name"] and you get back "Kyaw Kyaw".
A list makes you fetch data by position, such as 0, 1 or 2. A dict lets you fetch it by a meaningful name such as "name", "age" or "city". Each key can appear only once, and its value can be changed at any time.
Problem → Why → Solution
The problem: parallel lists drift out of sync
Suppose a shop stores product names and prices in two separate lists. To find the price of mango you first search the names list for its index, then read the prices list at that index. One day someone removes a product from the names list only, every later price shifts by one position, and mango now shows banana's price. No error is raised.
names = ["apple", "banana", "mango"]
prices = [500, 300, 1200]
names.remove("apple") # prices list was not updated!
index = names.index("mango")
print("mango costs", prices[index]) # 300: banana's old priceWhy does this bug happen?
The link between a name and its price lives only in the two lists sharing a position, and Python knows nothing about that link, so it cannot protect it. With a dict such as prices = {"apple": 500, "mango": 1200}, name and price form a single pair: del prices["apple"] cannot shift mango's price, and there is no index to search for at all.
Core concept: hashable keys mapped to values
You write a dict as key: value pairs inside curly braces, {"name": "Kyaw Kyaw", "age": 30}, or build one with dict(name="Kyaw Kyaw", age=30). Like a set, it stores keys by hash, so looking up a key stays fast no matter how big the dict grows. That is why keys must be hashable, such as str, int or tuple, while values can be anything, including lists and other dicts. Writing the same key twice keeps only the last value.
Since Python 3.7 the language guarantees that a dict remembers insertion order. Changing the value of an existing key keeps its position; only deleting the key and adding it again moves it to the end.
There are two ways to read. d[key] raises KeyError when the key is missing, so use it where the key must exist. d.get(key) returns None for a missing key, and d.get(key, default) returns your default instead. Writing has a single form, d[key] = value: it updates the value if the key exists and adds a new pair if it does not. To delete, use del d[key] (KeyError if missing) or d.pop(key, default), which also returns the removed value.
key in d checks keys only, never values. Looping with for key in d also gives you keys. Use d.values() when you need the values, and for key, value in d.items() when you need both. These methods return view objects that look into the dict, so wrap them in list(), as in list(d.keys()), when you want a real list. Because every key is unique, a dict is also the natural tool for counting and grouping, as the deeper section shows.
- Hash the key label
- Open the matching drawer directly
- Found: value. Missing: KeyError
- Assigning replaces the contents
get() is the polite way to open a drawer: when it does not exist you get your default back instead of an error.
General pattern
mapping = {key1: value1, key2: value2}
mapping[key] # read, KeyError if missing
mapping.get(key, default) # read, default if missing
mapping[key] = new_value # update or insert
del mapping[key] # delete (KeyError if missing)
mapping.pop(key, default) # delete and return the value
for key, value in mapping.items():
...Reading, writing and deleting all put the key in square brackets. Where a key might be absent, the default argument of get() and pop() prevents the error. items() hands the loop each key and value together.
Example: managing one person's profile
We build a profile dict for Kyaw Kyaw, then read, change, add and delete entries. After that we look at keys, values and items, and prove what in actually checks. (Loops are covered in detail in lesson 18, but a simple for loop over items() appears here.)
person = {"name": "Kyaw Kyaw", "age": 30, "city": "Yangon"}
print(person)
print(type(person).__name__, len(person))
print(person["name"])
print(person.get("email"))
print(person.get("email", "no email yet"))
person["age"] = 32
person["email"] = "kyaw@example.com"
del person["city"]
print(person)
print(list(person.keys()))
print(list(person.values()))
for key, value in person.items():
print(f"{key}: {value}")
print("age" in person, "Yangon" in person)Code breakdown
- Line 5
print(person["name"])The "name" key is certain to exist, so square brackets are fine. Writing person["email"] here instead would raise KeyError on this line.
- Lines 6-7
print(person.get("email", "no email yet"))There is no email key yet, so get() returns None on the first line and the default string on the second. The program keeps running.
- Lines 9-11
person["email"] = "kyaw@example.com"Same syntax, two effects: age already exists, so its value changes, while email is new and is added at the end. del removes the city pair. Notice in the output that age keeps its position.
- Line 17
for key, value in person.items():items() yields (key, value) tuples, and the loop unpacks each into two variables, in insertion order.
- Line 20
print("age" in person, "Yangon" in person)in checks keys only, so "age" is True and "Yangon" is False. Even before city was deleted it would have been False, because "Yangon" was a value, not a key.
{'name': 'Kyaw Kyaw', 'age': 30, 'city': 'Yangon'}
dict 3
Kyaw Kyaw
None
no email yet
{'name': 'Kyaw Kyaw', 'age': 32, 'email': 'kyaw@example.com'}
['name', 'age', 'email']
['Kyaw Kyaw', 32, 'kyaw@example.com']
name: Kyaw Kyaw
age: 32
email: kyaw@example.com
True False
Counting, grouping and merging
The most common dict job is counting. counts[word] = counts.get(word, 0) + 1 starts from 0 the first time and increments an existing count afterwards. setdefault(key, []) inserts an empty list when the key is missing and returns the existing list otherwise, which makes grouping easy. Since Python 3.9, a | b merges two dicts, and the right-hand value wins when a key appears in both.
words = ["tea", "coffee", "tea", "juice", "tea", "coffee"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
by_length = {}
for word in words:
by_length.setdefault(len(word), []).append(word)
print(by_length)
defaults = {"theme": "light", "lang": "en"}
user = {"lang": "my"}
print(defaults | user)In real projects
Where this shows up in real projects
Web APIs return JSON, and json.loads() turns it into a dict, so every piece of code that reads an API response is dict code. APIs often leave out optional fields, which is why reading them with get(), as in response.get("phone"), keeps production code from crashing. Configuration, HTTP headers and Django template contexts are all dicts too.
An inventory system keys stock counts by product code and increments them with inventory.get(code, 0) + qty when a delivery arrives; the report then walks sorted(inventory) for a stable order. A cache is a dict as well: store each computed result under its input as the key and you never compute it twice. For structured records whose fields are always the same, consider a dataclass instead, because Python cannot catch a misspelled dict key.
Common mistakes
Common mistakes
1. Reading a maybe-missing key with []
user["phone"] stops with KeyError: 'phone' for a user without that field. Read optional keys with user.get("phone", ""). Note that get() cannot tell a missing key from a key whose stored value is None; when that difference matters, check "phone" in user first.
2. Searching for a value with in
"Yangon" in person is False even when city holds that value, because in only looks at keys. Search values explicitly with "Yangon" in person.values().
3. Adding or deleting keys while looping
Deleting or adding keys inside for key in d: raises RuntimeError: dictionary changed size during iteration. Loop over a copy with for key in list(d):, or build a new dict instead.
4. Assuming copy() is deep
d.copy() and d | other are shallow: nested lists and dicts are shared with the original, so editing a nested list in the copy changes the original too. Use copy.deepcopy() when nested data must be fully separate.
Best practices
Best practices
- Use d[key] where the key must exist, so a missing key surfaces as a KeyError and points straight at the bug.
- Read optional fields of outside data (API responses, forms, files) with get() and a sensible default.
- Sort keys with sorted() for reports and test output, so the result does not depend on the order data arrived in.
Mini challenge
Mini challenge: update a shop's stock
Merge a delivery dict into a fruit shop's inventory, remove apple from the list, and print a report in name order.
- Add every fruit from delivery into inventory with the get(fruit, 0) pattern, including new ones like papaya
- Remove apple with pop() and print how many were removed
- Print each name and quantity on its own line in sorted() order
- Print the total item count and whether grape exists, without any KeyError
inventory = {"apple": 12, "banana": 3, "mango": 0}
delivery = {"banana": 10, "mango": 4, "papaya": 6}
# TODO: for each fruit, qty in delivery.items(): add qty to inventory
# TODO: pop "apple" (default 0) and print the amount moved out
# TODO: print every fruit in sorted order, e.g. "banana 13"
# TODO: print the total of all quantities
# TODO: print whether "grape" is a key, and its count via get()Expected: apple stock moved out: 12 banana 13 mango 4 papaya 6 total items: 23 False 0
Show hint
inventory[fruit] = inventory.get(fruit, 0) + qty works whether or not the key exists. Align columns with f"{name:<8}{qty:>3}", and total with sum(inventory.values()).
Show solution
inventory = {"apple": 12, "banana": 3, "mango": 0}
delivery = {"banana": 10, "mango": 4, "papaya": 6}
for fruit, qty in delivery.items():
inventory[fruit] = inventory.get(fruit, 0) + qty
sold_out = inventory.pop("apple", 0)
print("apple stock moved out:", sold_out)
for name in sorted(inventory):
print(f"{name:<8}{inventory[name]:>3}")
print("total items:", sum(inventory.values()))
print("grape" in inventory, inventory.get("grape", 0))Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A dict pairs each hashable key with a value and remembers insertion order.
- d[key] raises KeyError when missing; d.get(key, default) returns the default.
- d[key] = value both updates and inserts; del and pop() delete.
- in checks keys only, and items() gives key and value together in a loop.
The Python Tutorial — Python Software Foundation