An inventory stores separate details for each product code.
What You Need to Understand
A nested dictionary groups structured values, such as product records keyed by ID. Use consecutive key lookups or explicit loops to reach inner fields.
When to Use It
An inventory stores separate details for each product code.
Step-by-Step Python Example
inventory = {
"P1": {"name": "Pen", "quantity": 8},
"P2": {"name": "Notebook", "quantity": 3},
}
print(inventory["P1"]["name"])
inventory["P2"]["quantity"] += 2
print(inventory["P2"])
How the Example Works
The outer key chooses the product record; the inner key selects a field within that record.
Example Output
Pen
{'name': 'Notebook', 'quantity': 5}
A 1
B 2
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
inventory = {"A": {"qty": 1}, "B": {"qty": 2}}
for code, record in inventory.items():
print(code, record["qty"])
Important Behavior and Edge Cases
Nested structures can fail at either lookup level. Validate external data or use safe access patterns when keys are optional.
Try It Yourself
Loop over product codes and print each quantity.
Common Beginner Mistakes
- Nested structures can fail at either lookup level. Validate external data or use safe access patterns when keys are optional.
- Treating missing dictionary keys, replacement precedence, and shallow copies as if they had identical behavior in every context.
Key Takeaways
- A nested dictionary groups structured values, such as product records keyed by ID.
- The outer key chooses the product record; the inner key selects a field within that record.
- Nested structures can fail at either lookup level.