Part 04 / Topic 4 of 11
Dictionary (dict)
A dict stores key โ value pairs, like a phone book: you look up a name (the key) to get a number (the value). Keys are unique and must be hashable (fixed values like str, int, or a tuple of those; see the ๐ box in section 3). A list cannot be a key. Look up by key, not by position. Dicts keep the order you added keys in.
Real-world example: a phone book and a student record.
phone_book = {"Asha": "98450-11111", "Ravi": "99000-22222"}
print(phone_book["Asha"]) # 98450-11111
print(phone_book.get("Meena")) # None
print(phone_book.get("Meena", "Not saved")) # Not saved
phone_book["Meena"] = "97000-33333" # add a new key
phone_book["Ravi"] = "99000-44444" # change a value
phone_book.update({"Karan": "96000-55555"}) # add/change many
del phone_book["Asha"] # delete a key
print(list(phone_book.keys())) # ['Ravi', 'Meena', 'Karan']
print(len(phone_book)) # 3
print("Ravi" in phone_book) # True (checks keys)
for name, number in phone_book.items():
print(f"{name}: {number}")
# Ravi: 99000-44444
# Meena: 97000-33333
# Karan: 96000-55555
Nested dicts: a dict whose values are dicts (or lists).
students = {
"S01": {"name": "Asha", "marks": {"maths": 92, "science": 88}},
"S02": {"name": "Ravi", "marks": {"maths": 75, "science": 81}},
}
print(students["S01"]["name"]) # Asha
print(students["S02"]["marks"]["science"]) # 81
students["S02"]["marks"]["maths"] = 79 # change a nested value
for roll, info in students.items():
total = sum(info["marks"].values())
print(f"{roll} {info['name']}: {total}")
# S01 Asha: 180
# S02 Ravi: 160
| Method | What it does |
|---|---|
d[key] |
get value (KeyError if missing) |
d.get(key, default) |
get value or default (no error) |
d[key] = value |
add or change |
d.update(other) |
add / change many pairs |
del d[key] / d.pop(key) |
remove a key |
d.keys() / d.values() / d.items() |
views for looping |
๐ Going deeper: dicts keep insertion order since Python 3.7. Key lookup is fast (hashing, like sets), so a key must be hashable: a tuple of strings works, a list does not.
d.setdefault(key, default)returns the value and insertsdefaultfirst if the key is missing.keys(),values()anditems()are live views: they show changes to the dict right away.
Done here? The practice set for Part 4 โ 8 exercises with solutions โ is on the part page.