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

Julian Cardona
seal-mask
.a{fill-rule:evenodd;}techdegree
Julian Cardona
Python Web Development Techdegree Student 4,894 Points

word_count() Not working

I keep getting the question wrong even though I get the correct count for each word in Jupyter Notebook

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(x):
    xx = x.lower()
    new_list = []
    new_count = []
    for word in xx.split():
        new_list.append(word)
    for word in xx.split():
        new_count.append(xx.count(word))

    my_dict = dict(zip(new_list,new_count))
    return my_dict

1 Answer

Greg Kaleka
Greg Kaleka
39,021 Points

Hi Julian,

The problem is that with this line:

new_count.append(xx.count(word))

you're counting the occurrences of word in the string xx. This works fine for most words, and will actually give you the count of the occurrences of the whole word. However, if you have a short word like "a", "I", "am", "or", etc. it will count every occurrence of that string, regardless of whether or not it's a whole word. So if xx is "i am indivisible" and you're counting "i", you'll get a count of 5! The letter i shows up 5 times.

Instead, check the count on the list xx.split(). That will check how many times the word matches a list item, which is a whole word. Make sense?

Note you're using xx.split() a lot - maybe store that in a variable. Up to you, though.

Let me know if you can solve it now!

Cheers :beers:

-Greg