How to Count the frequencies in a list using a dictionary in Python?
A dictionary can be used to count the frequencies of elements in the list. Python example we will discuss how to count the frequencies in a list using a dictionary in Python.
Some of the topics which will be helpful for understanding the program implementation better are:
1. Counting Frequencies Using a Dictionary
The keys in a dictionary must be unique, while values can be duplicated. We can use this property to count the frequencies of elements in a list by treating each element in the list as a key in a dictionary and incrementing its value for each occurrence.
Now let’s implement a program to count the frequencies of the elements in Python.
fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana', 'kiwi', 'apple']
fruit_freq = {}
for fruit in fruits:
if fruit in fruit_freq:
fruit_freq[fruit] += 1
else:
fruit_freq[fruit] = 1
print(fruit_freq)Output
{'apple': 3, 'banana': 3, 'orange': 1, 'kiwi': 1}For each fruit, we check if it is already a key in fruit_freq. If it is, we increment its value by 1 otherwise we add it to fruit_freq with a value of 1. Finally, we print fruit_freq to verify that the frequencies have been counted correctly.
2. Using the collections Module
The collections module in Python provides a built-in Counter class that can be used to count the frequencies of elements in a list. The Counter object automatically counts the frequencies of each element in the list.
Here’s an example:
from collections import Counter fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana', 'kiwi', 'apple'] fruit_freq = Counter(fruits) print(fruit_freq)
Output
Counter({'apple': 3, 'banana': 3, 'orange': 1, 'kiwi': 1})3. Conclusion
In this Python example, we discussed multiple ways to count the frequencies in a list using a dictionary, one with a custom implementation and another using the Counter class.
Helpful Links
Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.
Also for examples in Python and practice please refer to Python Examples.
Complete code samples are present on Github project.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?