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

wordcount.py runs as expected on Workspaces, but doesn´t pass on the challenge

I tried several times... and after checking other posts I know my error is not the split("")...

What am I missing here??

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.

count = 1
wordcount = {}

def word_count(x):
    word = x.lower().split() # hago lista. Cada palabra es un item en la lista
    for z in word:
        if z in wordcount.keys():
            wordcount[z] = count + 1
        else:
            wordcount[z] = count
    return wordcount

4 Answers

wordcount = {}

def word_count(x):
    word = x.lower() # hago lista. Cada palabra es un item en la lista
    for z in word.split():
        if z in wordcount.keys():
            wordcount[z] += 1
        else:
            wordcount[z] = 1
    return wordcount

this is your code

>>> x = "I do not like it Sam I Am"
>>> count = 1
>>> wordcount = {}
>>> def word_count(x):
...     word = x.lower().split()
...     for z in word:
...             if z in wordcount.keys():
...                     wordcount[z] = count + 1
...             else:
...                     wordcount[z] = count
...     return wordcount
...
>>> word_count(x)
{'do': 1, 'like': 1, 'sam': 1, 'i': 2, 'am': 1, 'it': 1, 'not': 1}
>>> x = "I do not like it Sam I Am am am sam sam sam"
>>> word_count(x)
{'do': 2, 'like': 2, 'sam': 2, 'i': 2, 'am': 2, 'it': 2, 'not': 2}

Thanks ASHOK. I checked your code and we solved things in a different order... but all steps are there.

I tried the other suggested string and the count of words was correct.

I still can see what I am doing wrong.

Ok... got it. It's working now. I saw my mistake.

Much appreciated ASHOK