Counting the Frequencies in a List Using Dictionary in Python
Counting the frequencies of items in a list using a dictionary in Python can be done in several ways. For beginners, manually using a basic dictionary is a good starting point.
Using Manual Method
It uses a basic dictionary to store the counts, and the logic checks whether the item is already in the dictionary. If it is, the count is incremented; if it’s not, the item is added to the dictionary with an initial count of 1.
a = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']
# Create an empty dictionary to store the counts
b = {}
# Loop through the list
for c in a:
# If the item is already in dictionary, increase its count
if c in b:
b[c] += 1
# If the item is not in dictionary, add it with a count of 1
else:
b[c] = 1
print(b)
Output
{'apple': 2, 'banana': 3, 'orange': 1}
Let’s explore more methods to count the frequencies in a List Using Dictionory in Python.
Table of Content
Using a Default Dictionary (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
# List of items
a = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']
# Create a defaultdict with default value 0
b = defaultdict(int)
# Loop through the list
for c in a:
b[c] += 1
# Print the frequency of each item
print(dict(b))
Output
{'apple': 2, 'banana': 3, 'orange': 1}
Using get() Method
This will count the frequency of each item in the list using the get() method. The get() method 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']
# Create an empty dictionary to store the counts
b = {}
# Loop through the list
for c in a:
# Use get() to either return the current count or 0
#if the item is not in the dictionary
b[c] = b.get(c, 0) + 1
print(b)
Output
{'apple': 2, 'banana': 3, 'orange': 1}
Using List Comprehension
For small lists, we can also use a list comprehension along with the count() method to get the frequency of each item. But this method is not as efficient as the others since count() will loop through the entire list each time.
a = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']
# Create a list of unique items
b = list(set(a))
# Use list comprehension to count the frequency of each unique item
c = {item: a.count(item) for item in b}
# Print the frequency of each item
print(c)
Output
{'banana': 3, 'apple': 2, 'orange': 1}