Python Programming - Counting The Frequency Of Elements In A List Using A Dictionary

You can learn about Dictionaries in Python Programs with Outputs helped you to understand the language better.

Also Read: Java Program to Print nth Element of the Array

Python Programming – Counting The Frequency Of Elements In A List Using A Dictionary

Dictionaries can be used wherever you want to store attributes and values that describe some concept or entity. For example, you can use the dictionary to count instances of particular objects or states. Since each key must have a unique identifier, there cannot be duplicate values for the same key. Therefore, you can use the key to store the items of input data, leaving the value part to store the results of our calculations. For example, suppose you want to find out the frequency of each letter in a sentence, such as “A computer is a machine.” You could iterate through the characters of the sentence and assign each one to a key in the dictionary.

Example
Program using a dictionary to iterate through the characters.

# Program using dictionary to iterate through the characters
sentence = “Computer is a machine.”
characters = { }
for character in sentence:
characters[character] = characters.get(character,0) + 1
print(characters)RUN
>>>
{ ‘ C’ : 1, ‘m’: 2, ‘o’: 1, ‘u’: 1, ‘s’: 1, ‘r’: 1, ‘h’: 1 , ‘ i ‘ : 2 , ‘ p ‘ : 1 , ‘ c ‘ : 1 , ‘ . ‘ : 1, ‘a’: 2, ‘t’: 1, ‘n’: 1, ‘ ‘: 3, ‘e’: 2}
>>>

Example
Program to Count the frequency of elements in a list using a dictionary.

# Program to Count the frequency of elements
list= [ 2 , 3 , 3 , 5 , 4 , 4 , 2 , 2 ]
print ( ‘ Original List : ‘, list )
my_set=set ( list )
d=dict.fromkeys ( my_set,0 )
#print ( ‘ Dictionary with 0 values : ‘ )
#print(d)
for n in list:
d [n] =d[n]+1
print(‘Element : Frequency’)
print(d)RUN
>>>
Original List : [2, 3, 3, 5, 4, 4, 2, 2]
Element : Frequency
{2: 3, 3: 2, 4: 2, 5: l}
>>>

Let’s Try

Type the following program to count frequency of letters and see the output:

# Program to count frequency of letters
letter_counts = { }
for letter in “Programming”:
letter_counts[letter] = letter_counts.get(letter, 0) + 1
print ( letter_counts )

Leave a Reply

Your email address will not be published. Required fields are marked *