Sub topic 2
Handling Missing Keys and Indexes
Assume you know basic Python variables, lists, dictionaries, for loops, and functions. Nested data combines these types, so a lookup can fail at any level.
Handling missing keys and indexes
A missing dictionary key raises KeyError. A list index outside its range raises IndexError.
Use get() when a missing key has a reasonable default. Use in when you need to check before reading. Use try and except when missing data is an expected error case.
config = {"db": {"host": "localhost"}}
port = config.get("db", {}).get("port", 5432)
print(port) # 5432
if "cache" in config:
print(config["cache"])
try:
print(config["db"]["port"])
except KeyError:
print("The database port is missing")
scores = [10, 20]
if len(scores) > 2:
print(scores[2])The empty dictionary passed to the first get() prevents a second lookup from failing when "db" is absent.
Looping over nested structures
Use one loop for each nesting level. items() returns a dictionary's key and value together. enumerate() returns a list index and value together.
inventory = {
"fruit": {"apple": 3, "pear": 0},
"veg": {"kale": 5},
}
for category, items in inventory.items():
for name, count in items.items():
print(category, name, count)For a list of dictionaries, access fields inside the loop:
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88]},
]
for student in students:
for position, grade in enumerate(student["grades"]):
print(student["name"], position, grade)Building nested structures
Comprehensions create nested values compactly:
squares = {number: [number, number**2] for number in range(1, 4)}
print(squares) # {1: [1, 1], 2: [2, 4], 3: [3, 9]}For grouping, defaultdict(list) creates an empty list automatically.
from collections import defaultdict
by_letter = defaultdict(list)
for word in ["apple", "avocado", "banana"]:
by_letter[word[0]].append(word)
print(dict(by_letter))Exercise
Which exception does data["missing"] raise, and what should you use to supply a default value?
Show answer
It raises KeyError; use data.get("missing", default).