Computer >> Computer tutorials >  >> Programming >> Python

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