A report lists products together with quantities.
What You Need to Understand
dict.items() provides a live view of (key, value) pairs. It is particularly useful for loops that need both the key and its corresponding value.
When to Use It
A report lists products together with quantities.
Step-by-Step Python Example
stock = {"pen": 3, "paper": 7}
for product, quantity in stock.items():
print(product, quantity)
How the Example Works
Each iteration unpacks one key and one value. Dictionary insertion order is retained.
Example Output
pen 3
paper 7
[('a', 1)]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
data = {"a": 1}
print(list(data.items()))
Important Behavior and Edge Cases
The returned object is a view, not a snapshot; modifying the dictionary size during iteration can fail.
Try It Yourself
Convert a dictionary items view into a list of tuples.
Common Beginner Mistakes
- The returned object is a view, not a snapshot; modifying the dictionary size during iteration can fail.
- Using the wrong collection method for this operation without checking whether it mutates the object, returns a result, or raises on missing data.
Key Takeaways
dict.items()provides a live view of(key, value)pairs.- Each iteration unpacks one key and one value.
- The returned object is a view, not a snapshot; modifying the dictionary size during iteration can fail.