An inventory report needs the total quantity across products.
What You Need to Understand
dict.values() returns a live view of the values associated with dictionary keys. It is useful for summaries such as totals and averages.
When to Use It
An inventory report needs the total quantity across products.
Step-by-Step Python Example
quantities = {"pen": 5, "paper": 8, "folder": 2}
print(sum(quantities.values()))
print(list(quantities.values()))
How the Example Works
The total is 15, and the list snapshot contains all three quantities.
Example Output
15
[5, 8, 2]
9.0
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
scores = {"a": 8, "b": 10}
print(sum(scores.values()) / len(scores))
Important Behavior and Edge Cases
Values need not be unique. Checking a value in a values view can require scanning, unlike fast key membership.
Try It Yourself
Calculate the average of numerical dictionary values, guarding against an empty dictionary.
Common Beginner Mistakes
- Values need not be unique. Checking a value in a values view can require scanning, unlike fast key membership.
- 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.values()returns a live view of the values associated with dictionary keys.- The total is 15, and the list snapshot contains all three quantities.
- Values need not be unique.