w3resource

Python: Count the most common words in a dictionary

Python Collections: Exercise-31 with Solution

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.

Python Code Editor:

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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/collections/python-collections-exercise-31.php