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 (Retired) Dictionaries Word Count

Clara McKenzie
Clara McKenzie
691 Points

word_count() quiz doesn't like my solution but it does work - why can't I get a pass with this code?

def word_count( thestr ):
    index=0
    mydict={}
    mylist=thestr.split()
    while (index < len(mylist)):
        mydict[ mylist[index] ] = thestr.count(mylist[index])
        index += 1
    return mydict

1 Answer

I agree that your solution works, it was just that you implemented it in a different way than the exercise wanted. I managed to pass with this solution:

def word_count(thestr): 
    mydict = {} 
    mylist = thestr.split() 

    for word in mylist: 
        if word not in mydict:
            mydict[word] = 1
        else:
            mydict[word] += 1
    return mydict

Despite passing with the above code I liked your solution more; it was clean, although you can consider using a for loop instead of a while loop.

Clara McKenzie
Clara McKenzie
691 Points

Thanks eirikvaa, much appreciated. I guess it didn't want the dictionary entry to be over-written.

Yes, that might be it.