0
0
PythonHow-ToBeginner · 3 min read

How to Count Occurrences Using Dictionary in Python

You can count occurrences in Python by using a dictionary where keys are items and values are counts. Loop through your data and update the count for each item using dict[key] = dict.get(key, 0) + 1.
📐

Syntax

Use a dictionary to store counts. The key is the item, and the value is how many times it appears.

Example syntax:

  • counts = {} creates an empty dictionary.
  • counts[item] = counts.get(item, 0) + 1 increases the count for item by 1, or sets it to 1 if not present.
python
counts = {}
for item in data:
    counts[item] = counts.get(item, 0) + 1
💻

Example

This example counts how many times each fruit appears in a list.

python
fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counts = {}
for fruit in fruits:
    counts[fruit] = counts.get(fruit, 0) + 1
print(counts)
Output
{'apple': 3, 'banana': 2, 'orange': 1}
⚠️

Common Pitfalls

One common mistake is trying to increment a key that does not exist yet, which causes a KeyError. Using dict.get(key, 0) avoids this by providing a default count of 0.

Another pitfall is forgetting to initialize the dictionary before counting.

python
counts = {}
# Wrong way: causes KeyError if key not present
# counts['apple'] += 1

# Right way:
counts['apple'] = counts.get('apple', 0) + 1
📊

Quick Reference

OperationCode ExampleDescription
Create empty dictionarycounts = {}Start with an empty dictionary to store counts
Increment countcounts[item] = counts.get(item, 0) + 1Add 1 to count or set to 1 if new
Print countsprint(counts)Show the dictionary with all counts

Key Takeaways

Use a dictionary to map items to their counts for easy occurrence tracking.
Use dict.get(key, 0) to safely handle keys that are not yet in the dictionary.
Always initialize your dictionary before counting.
Loop through your data and update counts incrementally.
Printing the dictionary shows the final counts of all items.