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

Thomas Ross
Thomas Ross
4,634 Points

Stuck on Word Count Challenge

Not sure where I am going wrong; works for the test case and works for all the examples I've thrown at it so far.

# test cases
print(word_count("I do not like it Sam I Am"))
print(word_count("AM AM AM WITH WITH TOM TOM TOM TOM HI"))
print(word_count("55555 55555 55555 55555 55555 22 22 1"))
# output
> {'do': 1, 'i': 2, 'like': 1, 'am': 1, 'it': 1, 'sam': 1, 'not': 1}
> {'with': 2, 'tom': 4, 'am': 3, 'hi': 1}
> {'1': 1, '22': 2, '55555': 5}

Any ideas?

# 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(val):
    str_list = val.lower().split(" ")
    str_dict = {}
    for word in str_list:
        cnt = 0
        for cnt_word in str_list:
            if word == cnt_word:
                cnt += 1
                str_dict.update({word: cnt})
    return str_dict

1 Answer

Because you set "cnt" back to 0 every time you move through str_list the count will never be updated to more than 1. Its looking great other than that, you've got this!!

Thomas Ross
Thomas Ross
4,634 Points

Thanks for taking a look. I'm still not seeing it. I am setting the counter back to 0 but that is on the outer loop; not the inner, and if you look at the test cases above it is returning the right output for the test case and my own tests. Thanks again!