Lesson explanation
After this lesson, you will be able to:
Real responses and configurations often combine collections: a dictionary may hold a list of services, and each service may itself be a dictionary. Read a nested path one level at a time. config["services"] selects the list; [0] selects a record; ["name"] selects a field.
Nested collections are mutable. Changing a nested field through its path changes the original collection. The outer collection's type does not remove the mutability of objects inside it.
When a nested mapping is optional, use .get(key, {}) to obtain an empty dictionary as a fallback. Read an optional numeric value with .get(key, default) rather than a truthiness fallback: the value 0 can be intentional.
config = {"targets": [{"name": "staging", "port": 8081}, {"name": "prod", "port": 443}]}
print(config["targets"][1]["port"])Output:
443The first lookup returns a list; the second selects a dictionary within it.
limits = {"search": {"retries": 2, "timeout": 30}}
limits["search"]["retries"] += 1
print(limits["search"]["retries"])
print(limits["search"]["timeout"])Output:
3
30Only the retry setting changes.
jobs = [{"name": "index", "done": True}, {"name": "backup", "done": False}]
for job in jobs:
if job["done"]:
print(f"Finished: {job['name']}")Output:
Finished: indexThe loop variable is already one dictionary; no additional numeric index is needed.
settings = {"thresholds": {"api": 0}}
thresholds = settings.get("thresholds", {})
print(thresholds.get("api", 10))
print(thresholds.get("worker", 10))Output:
0
10A stored zero is preserved, but a missing key uses the fallback.
| Goal | Example |
|---|---|
| Read a nested field | data["jobs"][0]["status"] |
| Update a nested field | data["limits"]["api"] = 5 |
| Iterate records | for record in records: |
| Read an optional nested dictionary | data.get("limits", {}) |
| Preserve a stored zero | limits.get("api", 10) |
for record in records is not a numeric index.data["missing"] raises KeyError when a key is absent.dict.get("key") or default wrongly replaces valid falsy values such as 0.