count_words

Python Morsels Exercise

Count occurrences of each word in a string

2 bonuses 8 hints 13 solutions 1,698 users solved 125 reviews

When solving this exercise, make sure to hold off on searching directly for the answer on Google/StackOverflow. 🚫🔍

This is a fairly general exercise and there are a number of answers to it. I'd like you to struggle to come to an answer or two (or five?) on your own.

I want you to write a function that accepts a string and returns a mapping (a dictionary or dictionary-like structure) that has words as the keys and the number of times each word was seen as the values.

Your function should work like this:

>>> count_words("oh what a day what a lovely day")
{'oh': 1, 'what': 2, 'a': 2, 'day': 2, 'lovely': 1}
>>> count_words("don't stop believing")
{"don't": 1, 'stop': 1, 'believing': 1}

Bonus 1


This is just a preview of the problem statement.

This exercise includes 2 bonuses and 8 hint links.

To solve this exercise, sign in to your Python Morsels account.

A learning habit for experienced Pythonistas

Profile picture of Trey

My name is Trey Hunner and I hold Python trainings for teams. I've spent countless hours refining my most interesting Python exercises into Python Morsels, a Python skill-building platform for folks who already know Python. Python Morsels is design to help you deepen your Python skills every week.

Sign up for Python Morsels to access this exercise and many more.

Join Python Morsels ✨