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:

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'
]
from collections import Counter
word_counts = Counter(words)
top_four = word_counts.most_common(4)
print(top_four)

Sample Output:

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

Flowchart:

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

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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 Python skills with w3resource's quiz


Python: Tips of the Day

Unpack a Tuple:

>>> items = (0, 'b', 'one', 10,  11, 'zero')
>>> a, b, c, d, e, f = items
>>> print(f)
zero
>>> a, *b, c = items
>>> print(b)
['b', 'one', 10, 11]
>>> *_, a, b = items
>>> print(a)
11