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

anhedonicblonde
anhedonicblonde
3,133 Points

Question about word_count() function

For the word_count() challenge, I modified the solution and saved it as a script so I could run it in the Console and see how it worked. I used the code below but am getting a print of an empty dictionary. Can someone tell me why this is? If this was the solution, then why does it print an empty dictionary when explicitly given a string? (I ran the string as the argument for the word_count function first before naming a variable for it as you see here and had the same empty dictionary result)

def word_count(string):
    string_2 = string.lower()
    string_3 = string.split()
    dict = {}
    for word in dict:
        if word not in dict:
            dict[word] = 1
        else:
            dict[word] +=1

    print (dict)

string = "The quick brown fox jumped over the lazy dog"
word_count(string)

1 Answer

Hi!

You lower() and split(), but don't call either in the function. Line 3 and the for loop should be adjusted as follows:

def word_count(string):
    string_2 = string.lower()
    string_3 = string_2.split()
    dict = {}
    for word in string_3:
        if word in dict:
            dict[word] += 1
        else:
            dict[word] = 1
    print(dict)

Hope that helps!

Also- I try to avoid using dict as a variable

anhedonicblonde
anhedonicblonde
3,133 Points

Awesome !! It works perfectly now, and I understand what I missed (yay!). And duly noted re: dict - good advice to follow :) Thanks so much!!