A supply room counts labels recorded in a delivery.
What You Need to Understand
A dictionary can count repeated items by using each item as a key and storing its count as the value. Use get(item, 0) + 1 to handle the first occurrence.
When to Use It
A supply room counts labels recorded in a delivery.
Step-by-Step Python Example
items = ["pen", "folder", "pen", "paper", "pen"]
counts = {}
for item in items:
counts[item] = counts.get(item, 0) + 1
for item in sorted(counts):
print(item, counts[item])
How the Example Works
Every occurrence increments the appropriate value; the final dictionary contains one key per distinct item.
Example Output
folder 1
paper 1
pen 3
a
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
items = ["a", "b", "a"]
counts = {}
for item in items:
counts[item] = counts.get(item, 0) + 1
print(max(counts, key=counts.get))
Important Behavior and Edge Cases
Keys are case-sensitive. Normalize first only when Pen and pen should be the same product; avoid counting display labels that are not reliable identifiers.
Try It Yourself
Find the most frequent label in a short list using the counts dictionary.
Common Beginner Mistakes
- Keys are case-sensitive. Normalize first only when
Penandpenshould be the same product; avoid counting display labels that are not reliable identifiers. - Applying the example without a clearly defined policy for missing keys, matching identifiers, or validating external values.
Key Takeaways
- A dictionary can count repeated items by using each item as a key and storing its count as the value.
- Every occurrence increments the appropriate value; the final dictionary contains one key per distinct item.
- Keys are case-sensitive.