Counting the Frequencies in a List Using Dictionary in Python (original) (raw)

Last Updated : 25 Oct, 2025

Given a list of items, the task is to count the frequency of each item in Python. **For example:

**Input: ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']
**Output: {'apple': 2, 'banana': 3, 'orange': 1}

Let’s explore different methods to count frequencies efficiently using dictionaries.

Using Counter from collections

The Counter class from the collections module counts the frequency of each item in a list by creating a dictionary-like object where each unique item becomes a key and its count becomes the value.

Python `

from collections import Counter a = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana'] freq = Counter(a) print(dict(freq))

`

Output

{'apple': 2, 'banana': 3, 'orange': 1}

**Explanation:

Using defaultdict

The defaultdict from the collections module automatically initializes new keys with a default value (in this case, 0), so there's no need to explicitly check if the key exists before incrementing the count.

Python `

from collections import defaultdict

a = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana'] freq = defaultdict(int)

for item in a: freq[item] += 1

print(dict(freq))

`

Output

{'apple': 2, 'banana': 3, 'orange': 1}

**Explanation:

Using get() Method

This will count the frequency of each item in the list using get() method. It is used to return the current count of an item or 0 if the item is not yet in the dictionary.

Python `

a = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']

freq = {} for item in a: freq[item] = freq.get(item, 0) + 1

print(freq)

`

Output

{'apple': 2, 'banana': 3, 'orange': 1}

**Explanation:

Using Dictionary

This method manually counts items using a dictionary by checking if the key exists. If it exists, increment; otherwise, initialize to 1.

Python `

a = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']

freq = {} for item in a: if item in freq: freq[item] += 1 else: freq[item] = 1

print(freq)

`

Output

{'apple': 2, 'banana': 3, 'orange': 1}