This guide explains Iterating over Dictionary Keys, Values, and Items through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
Iterating over a dictionary directly visits its keys. .values() provides values and .items() provides key-value pairs. Destructuring those pairs makes reports easier to read.
When You Would Use This
Display a stock quantity for each product.
Step-by-Step Example
stock_by_product = {"Pen": 12, "Folder": 5}
for product_name, item_count in stock_by_product.items():
print(f"{product_name}: {item_count}")
How the Example Works
Each .items() element is a two-part tuple containing the key and its value. The loop assigns both names in one step.
Example Output
Pen: 12
Folder: 5
Try It Yourself
Loop only over the keys, then only over the values, and compare the outputs.
Common Beginner Mistakes
- Expecting direct dictionary iteration to produce values.
- Modifying dictionary keys while iterating through the dictionary.
- Assuming older programming languages’ arbitrary order rules apply to modern Python dictionaries.
Key Takeaways
- Iterating over a dictionary directly visits its keys.
- Each
.items()element is a two-part tuple containing the key and its value. - Avoid this mistake: Expecting direct dictionary iteration to produce values.