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

Leo Marco Corpuz
Leo Marco Corpuz
18,975 Points

dictionary word_count challenge

I couldn't think of any other way to count the number of key occurrences in a string other than the count method. Is this the right approach? Also, I'm not sure how to modify the for-loop in order to make the keys only appear once in the dictionary.

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(phrase):
    phrase=phrase.split(" ")
    dict_phrase={}
    for word in phrase:
       word=word.lower()
       value_count= phrase.count(word)
       dict_phrase[word]=value_count
    return dict_phrase

1 Answer

Steven Parker
Steven Parker
229,708 Points

The error message contains some hints: ":x:Bummer: Hmm, didn't get the expected output. Be sure you're lowercasing the string and splitting on all whitespace!"

It's suggesting that you convert the entire string to lowercase before you split it. Otherwise, when you apply the "count" method to "phrase", the word might not match.

And to split on "all whitespace" the "split" function should be given no argument. Giving it a space causes it to split on individual spaces and not combine them or consider other whitespace characters.

Happy coding! :christmas_tree: And for some holiday-season fun and coding practice, give Advent of Code a try! :santa: