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

Why doesn't my function pass the coding challenge? Its output is the same as the example.

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.

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(string):
    string = string.lower()
    string_list1 = string.split(" ")
    string_list2 = string_list1[:]
    string_dictionary = {}
    for item1 in string_list1:
        counter = 0
        index = 0
        for item2 in string_list2:
            if item2 == item1:
                counter += 1
                string_list2.pop(index)
            index +=1
        if counter > 0:
            string_dictionary[item1] = counter
    return string_dictionary

1 Answer

Steven Parker
Steven Parker
231,269 Points

The error message you get contains this hint: "Be sure you're lowercasing the string and splitting on all whitespace!"

For a "split" to work on "all whitespace", the argument should be left empty. Providing a space argument causes it split specifically (and only) on every space.

Also, it's not clear why you would "pop" anything from the second list, since by doing so you would be likely to get an inaccurate count when you encounter a repeated word again in the outer loop.