Python Morsels Exercise

Count occurrences of each word in a string

2 bonuses 6 hints 12 solutions 1,480 users solved 103 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, 6 hint links, and automated tests.

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 improve your Python skills every week through 1 hour of deliberate practice.

Let me help you write more beautiful Python code. Sign up for Python Morsels to access this exercise and many more.

Join Python Morsels ✨