How to use a Python dictionary for counting?

Hello everyone! I’m working on text analysis in Python and have stored my data from txt files in Python lists. Now, I need to count the frequency of words in the data. For instance, given this sample list:

data_list = ['a', 'random', 'data', 'containing', 'random', 'words']

I want to count the frequency of occurrence of each word in this list. I read that Python dictionaries can be useful for this task. Could anyone suggest how to do this using dictionaries and provide some example code? Thank you!

1 Like

Yes, you can use a Python dictionary to count the frequency of words in a list. Here’s an example code snippet that shows how to do it:

This code initializes an empty dictionary word_count . It then iterates over each word in data_list . If the word is already present in the dictionary, its count is incremented by 1. If the word is not present in the dictionary, it is added to it with a count of 1. Finally, the dictionary is printed, which contains the frequency of each word in the list.

1 Like

Hey @mubashir_rizvi! Here’s an approach using dictionaries to count the frequency of words in a list is to use the collections module in Python, specifically the Counter class. Here’s an example code snippet:

  • In this code, we import the Counter class from the collections module. We then create a Counter object called word_freq and pass in the data_list as an argument. The Counter class automatically counts the frequency of each element in the list and stores it in a dictionary-like object.
  • The output shows that the word “random” appears twice in the list, while each of the other words appears only once.

Hey @mubashir_rizvi, list comprehension method helps you to create a dictionary of word frequencies.

In the above code for each word in the data_list , the list comprehension counts the number of times that word appears in the list using the count method and adds an entry to the dictionary with the word as the key and its frequency as the value. Finally, it prints out the resulting dictionary of word frequencies.