w3resource logo


Python Exercises

Python: Count the occurrences of each word in a given sentence


Write a Python program to count the occurrences of each word in a given sentence.

Sample Solution :

Python Code :

def word_count(str):
    counts = dict()
    words = str.split()

    for word in words:
        if word in counts:
            counts[word] += 1
        else:
            counts[word] = 1

    return counts

print( word_count('the quick brown fox jumps over the lazy dog.'))

Console :

Copy and paste the above code and press "Enter key" to execute :

Post your code through Disqus