Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Counting the frequencies in a list using dictionary in Python
In this article we develop a program to calculate the frequency of each element present in a list.
Using a dictionary
Here we capture the items as the keys of a dictionary and their frequencies as the values.
Example
list = ['a','b','a','c','d','c','c']
frequency = {}
for item in list:
if (item in frequency):
frequency[item] += 1
else:
frequency[item] = 1
for key, value in frequency.items():
print("% s -> % d" % (key, value))
Output
Running the above code gives us the following result −
a -> 2 b -> 1 c -> 3 d -> 1
Using count()
Here we use the in-built count() function to count the number of occurrences of an item in the list.
Output
list = ['a','b','a','c','d','c','c']
frequency = {}
for item in list:
frequency[item] = list.count(item)
for key, value in frequency.items():
print("% s -> % d" % (key, value))
Running the above code gives us the following result >
a -> 2 b -> 1 c -> 3 d -> 1
Advertisements