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

Why isn't my word count function working? It is giving the correct output but it isn't being accepted.

Here is my code:

def word_count(string):
    lst = (string.lower()).split(" ")
    dc = {}
    for item in lst:
        num = lst.count(item)
        dc["{}".format(item)] = "{}".format(num)
    return dc

When this code is run using the string provided in the question ("I do not like it Sam I Am"), it gives the exact same output ({'i': '2', 'do': '1', 'not': '1', 'like': '1', 'it': '1', 'sam': '1', 'am': '1'} ). I'm not sure why it isn't being accepted by treehouse though.

1 Answer

Why are the values strings? They should be integers.

Replace this line:

dc["{}".format(item)] = "{}".format(num)

With this:

dc["{}".format(item)] = num

Also, I believe that you need to split on all whitespace, not just spaces. Try using .split() instead of .split(" ").

Thanks, this really cleared things up.