Read Nested Dictionaries Safely
Core idea
A nested dictionary stores other dictionaries as values. For rooms["A"]["seats"], Python retrieves the inner dictionary first and then its seats value. If your data contract guarantees that each room value is a dictionary, use rooms.get("A", {}).get("seats", 0) to handle absent keys at either level.
rooms = {"A": {"seats": 12}, "B": {"seats": 8}}print(rooms["A"]["seats"])The first lookup selects a room; the second selects its seats.
Handle missing keys
rooms = {"A": {"seats": 12}, "B": {}}print(rooms.get("B", {}).get("seats", 0))print(rooms.get("C", {}).get("seats", 0))An empty inner mapping and a missing outer key both use the fallback.
Update an inner value
rooms = {"A": {"seats": 12}}rooms["A"]["seats"] = 14print(rooms)The inner dictionary is mutable and the updated value is visible through rooms.
Common mistake
get does not validate the type of a stored value. If rooms["A"] is None rather than a dictionary, a chained get call raises AttributeError. The examples require dictionary-valued room entries.
Practice
Create a mapping of two devices, each with a nested battery count. Read a known count and use a fallback for an absent device.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Nested dictionaries
Check your understanding of nested dictionaries.
What is printed?
d = {"A": {"n": 7}}print(d["A"]["n"])What is printed?
d = {"A": {}}print(d.get("A", {}).get("n", 0))What is printed?
d = {"A": {"n": 1}}d["A"]["n"] = 3print(d["A"]["n"])What must be true of stored outer values for chained get calls to work as shown?