Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Dictionaries Word Count

Davis Mercier
Davis Mercier
7,805 Points

Word Count Objective

Hello,

I've been working on the word count challenge. I have a solution that I'm pretty sure is correct (I've run it through the console with several strings and it always has produced the correct output), but every time I submit the answer is rejected. This function should take a string and return a dictionary where every word is a key and the assigned value is the number of times the words appears.

Example:

word_count("Hello hello is there anybody in there")

{'hello': 2, 'is': 1, 'there': 2, 'anybody': 1, 'in': 1}

Code is below:

def word_count(string): list_of_words = string.lower().split(" ")

dictionary = {}

for word in list_of_words:
    count = 0
    for word_again in list_of_words:
        if word == word_again:
            count += 1
    dictionary[word] = count

return dictionary

Any help you can offer would be appreciated.

wordcount.py
# E.g. word_count("I do not like it Sam I Am") gets back a dictionary like:
# {'i': 2, 'do': 1, 'it': 1, 'sam': 1, 'like': 1, 'not': 1, 'am': 1}
# Lowercase the string to make it easier.

def word_count(string):
    list_of_words = string.lower().split(" ")

    dictionary = {}

    for word in list_of_words:
        count = 0
        for word_again in list_of_words:
            if word == word_again:
                count += 1
        dictionary[word] = count

    return dictionary

1 Answer

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Hey Davis,

You've pretty much got it exactly, except for just one tiny error.
Now, it's really not very clear in the instructions, nor is the error any indication, but the problem is the split() method.

Think about everything that could be passed into the function. Someone may have used the enter key or the tab to space the words... So... you should probably split on all whitespace and not just spaces as it is now.

Just fix up the split() call to include all whitespace (remember this is done by passing in no parameters to the method call).

Other than that... Awesome job!! :thumbsup: :)

:dizzy:

Davis Mercier
Davis Mercier
7,805 Points

Makes perfect sense, thanks for the reply!