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

I don't understand this problem very well or what's wrong with this code. I need a lot of help I'm afraid.

I just don't understand what's going on here. I need help.

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.
import collections 
def word_count(string): 
    string_list=string.lower().split(" ")
    headache={}
    for word in string_list: 
        if word in string_list: 
            headache[word]+=1
        else: 
            headache[word]=1
    return headache 

3 Answers

Steven Parker
Steven Parker
231,269 Points

You're really close! Inside your loop, instead of testing if word is in string_list (you know it is, since the loop got it from there), you probably meant to test if it is in the dictionary headache.

And to split on any white space, leave out the argument to split.

Oh I see! I think I added the "" inside of the .split() after reading through a bunch of possible solutions and didn't quite understand that it needed to be blank. Thank you very much for your help. I'm still getting the hang of how to think about dictionaries.

def word_count(arg):
    words = arg.lower().split()
    keys = set(words)
    ret = dict(zip(keys, [0 for  _ in range(len(keys))]))
    for key in words:
        if ret.get(key) is not None:
            ret[key] += 1
    return ret