w3resource

Python: Count the most common words in a dictionary


31. Count the Most Common Words in a Dictionary

Write a Python program to count the most common words in a dictionary.

Sample Solution:

Python Code:

# Create a list 'words' containing various color names and other words
words = [
   'red', 'green', 'black', 'pink', 'black', 'white', 'black', 'eyes',
   'white', 'black', 'orange', 'pink', 'pink', 'red', 'red', 'white', 'orange',
   'white', "black", 'pink', 'green', 'green', 'pink', 'green', 'pink',
   'white', 'orange', "orange", 'red'
]

# Import the Counter class from the collections module
from collections import Counter

# Create a Counter object 'word_counts' to count the occurrences of words in 'words'
word_counts = Counter(words)

# Find the four most common words using 'most_common' and store them in 'top_four'
top_four = word_counts.most_common(4)

# Print the four most common words
print(top_four) 

Sample Output:

[('pink', 6), ('black', 5), ('white', 5), ('red', 4)]

Flowchart:

Flowchart - Python Collections: Count the most common words in a dictionary.

For more Practice: Solve these Related Problems:

  • Write a Python program to extract words and their counts from a dictionary and then sort them by frequency using sorted().
  • Write a Python program to use collections.Counter on the values of a dictionary and output the most common words.
  • Write a Python program to implement a function that returns the top n most common words from a dictionary of word counts.
  • Write a Python program to merge two dictionaries of word frequencies and then print the most common words overall.

Go to:


Previous: Write a Python program to count the occurrence of each element of a given list.
Next: Write a Python program to find the class wise roll number from a tuple-of-tuples.

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.