An inventory report contains multiple products with different quantities.
What You Need to Understand
A list of dictionaries is a common beginner-friendly structure for tabular records. Iterate through each dictionary, then access specific named fields.
When to Use It
An inventory report contains multiple products with different quantities.
Step-by-Step Python Example
products = [{"name": "Pen", "stock": 5}, {"name": "Folder", "stock": 0}]
for product in products:
if product["stock"] > 0:
print(product["name"], "available")
How the Example Works
Each loop iteration receives a dictionary. The stock lookup decides whether to print the product name.
Example Output
Pen available
6
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
items = [{"qty": 2}, {"qty": 4}]
print(sum(item["qty"] for item in items))
Important Behavior and Edge Cases
Validate record shapes when data comes from outside the program; a missing stock key raises KeyError.
Try It Yourself
Calculate the total stock across the product records.
Common Beginner Mistakes
- Validate record shapes when data comes from outside the program; a missing
stockkey raisesKeyError. - Treating missing dictionary keys, replacement precedence, and shallow copies as if they had identical behavior in every context.
Key Takeaways
- A list of dictionaries is a common beginner-friendly structure for tabular records.
- Each loop iteration receives a dictionary.
- Validate record shapes when data comes from outside the program; a missing
stockkey raisesKeyError.