Counting the Frequencies in a List Using Dictionary in Python
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.
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:
- Counter(a) creates a dictionary-like object where keys are items and values are their counts.
- dict(freq) converts the Counter object to a standard dictionary.
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.
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:
- defaultdict(int) creates a dictionary where each missing key defaults to 0.
- For each item in a, freq[item] += 1 increments its count.
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.
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:
- freq.get(item, 0) returns the current count of item or 0 if it doesn’t exist.
- Adding 1 increments the count.
Using Dictionary
This method manually counts items using a dictionary by checking if the key exists. If it exists, increment; otherwise, initialize to 1.
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}