Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (2016, retired 2019) Dictionaries Word Count

Why is my solution not working? It returns correct answer in my terminal.

def word_count(string): ... word_list = string.split(" ") ... freq = {} ... lower_case = lower(word_list) ... for word in lower_case: ... if (word in freq): ... freq[word.lower()] +=1 ... else: ... freq[word.lower()] = 1 ... return freq

def lower(lst): ... new = [] ... for item in lst: ... item = item.lower() ... new.append(item) ... return new ...

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 lower(lst):
    new = []
    for item in lst:
        new.append(item.lower())
    return new

def word_count(string):
        word_list = string.split(" ")
        freq = {}
        lower_case = lower(word_list)
        for word in lower_case:
            if (word in freq):
                freq[word.lower()] += 1
            else:
                freq[word.lower()] = 1
        return freq

1 Answer

Steven Parker
Steven Parker
218,814 Points

I'm surprised that this worked outside of the challenge, as I'm not familiar with a "lower" function that would convert an entire list into lower case and return it as another list. But you can simply convert the string before you split it.

Also, the challenge wants you to split words on "all whitespace", so the argument to "split" should be left empty or set to None:

        lower_case = string.lower().split()

And since you converted the string already, you won't need to convert the individual words:

                freq[word] += 1

Thanks!! I don't know why several other solutions I tried worked in my terminal and not in the treehouse workspace, but I used your lower_case function and it passed :)