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

Unable to complete python word-count challenge

Hello everyone.

I'm having difficulties with the python code challenge found here: https://teamtreehouse.com/library/python-collections-2/dictionaries/word-count

I hope somebody will be able to help me understand how to complete this challenge.

Below is the code I have written:

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):
    lowered_string = string.lower()
    word_list = lowered_string.split(" ")
    dictionary = {}
    for word in word_list:
        dictionary.update({word: 0})
    for word in word_list:
        dictionary[word] = dictionary[word] + 1
    return dictionary
Steven Tagawa
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Steven Tagawa
Python Development Techdegree Graduate 14,438 Points

I copied your code into a Workspace and it seemed to work fine. (It returned a dictionary with the correct word counts for the example string.) Are you getting an error message, and if so, what is it?

2 Answers

Steven Parker
Steven Parker
230,995 Points

You're really close! And your error message contains a hint: "Bummer: Hmm, didn't get the expected output. Be sure you're lowercasing the string and splitting on all whitespace!"

To split on "all whitespace" you should leave the argument to the "split" function empty. Giving it a space causes it to split on individual spaces exclusively. For more details, see the documentation on str.split().

Woops! Thanks Steven Parker, I guess I was thinking like JavaScript, not Python!

Silly me!

Thanks for your answer!

akoniti
akoniti
1,410 Points

Your seems to work in a quick test with a small change:

word_list = lowered_string.split()

You'll notice I removed the quotation marks from your split method arguments.

Yeah, that seems to have been the problem! Thanks akonti!