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

Danilo Livassan
Danilo Livassan
2,199 Points

I cant figure out why my code is wrong.

I have tested on my computer and thats return the same output. But not in the same order. {'do': 1, 'like': 1, 'sam': 1, 'i': 2, 'am': 1, 'it': 1, 'not': 1}

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):
    if type(phrase) is not str:
        return None
    phrase = phrase.lower().strip()
    phrase = phrase.replace(',', ' ')
    phrase = phrase.replace('.', ' ')
    dict_words = {}
    phrase = phrase.split(' ')
    for word in phrase[:]:
        if word != ' ' and word != '':
            if word in dict_words:
                dict_words[word] += 1
            else:
                dict_words[word] = 1
    return dict_words

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

You are SO close. The challenge asks you to split on WHITESPACE, instead of a literal SPACE. Use .split() with no arguments to default to whitespace. This will pass the challenge.

Additionally, you do not need to strip() or replace the commas and periods with spaces. The test data does not seem to contain any punctuation or newline characters.

Post back if you need more help. Good luck!

Arturo Barradas
PLUS
Arturo Barradas
Courses Plus Student 7,526 Points

Hello,

I just cleaned your code and tested it in the system and it has passed. 1) strip() is not needed your are not taken anything like return at the end 2) split will take care of taken each word, you do not need to specify (' ') (blank space) 3) in the for loop it is not needed the split range you are using. It is enough to take just phrase instead of phrase[:] 4) The if following the for is not really needed.