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

Nantawat Laothong
Nantawat Laothong
10,277 Points

I don't know how to fix my code. Could it be a bug?

Hi, guys. This is the challenge task. I need to make a function that count how many times a word occurs in a string and construct a dictionary using the informations. The keys in the dictionary will be each of the words in the string, lowercased. The values will be how many times that particular word appears in the string.

If you can help me, I would greatly appreciate it.

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):
    # make word lower case
    string = string.lower()
    # put each word into a list
    list_of_word = string.split(" ")
    # create dict
    empty_dict = {}
    for word in list_of_word:
    # update dict
        empty_dict.update({word:list_of_word.count(word)})

    return(empty_dict)

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,426 Points

The challenge is asking for all white space. The code is splitting on a literal SPACE. Remove the quoted space and used the default empty argument to mean all white space: .split()

According to the str.split() docs:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

Nantawat Laothong
Nantawat Laothong
10,277 Points

Thank you so much, Chris. It works!! You are a lifesaver!