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

Richárd Orbán
Richárd Orbán
6,208 Points

Word Count counts characters instead of words

I found that all I had to do for it to work was to use the split() and lower() method on the string in the for loop, but I'd just like to know why that fixes it.

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 word_count(s):
    s.split()
    d = {}
    for item in s:
        if item in d:
            d.update({item: d.get(item)+1})
        else:
            d.update({item: 1})
    return d

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there, Richárd Orbán ! My guess here is that you ended up with something that looked a bit like this in your for loop.

 for item in s.lower().split():

This makes the string in question lower case and split on every iteration. And it's working from that string lowercased and split.

In your original code you had s.split(). And it does split the string, but the results of that aren't ever assigned anywhere. They are just sort of floating around out there in Python limbo and will go up for garbage collection. Your original code that you posted here would have worked if you had both turned it to lower case and split it and assigned the values back into s.

Instead of:

s.split()

You could have done:

s = s.lower().split()

Then when it evaluates s in the for loop it will be evaluating the correct thing. Again, when you do s.split() it isn't overwriting the original value of s so when it got down to the for loop it's still in its original unsplit condition.

Hope this helps! :sparkles:

Richárd Orbán
Richárd Orbán
6,208 Points

I didn't even think of that, thank you!