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

Could someone explain why this code isn't passing?

I tried this code with multiple string examples in workspaces and it seems to run just fine. I'm probably missing something really obvious, but i've been staring at this for about an hour so i'm getting a lil frustrated. Any help would be appreciated. Thanks

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(astring):
    astring = astring.lower()
    my_dict = {}
    for x in astring.split():
        my_dict[x] = astring.count(x)
    return my_dict

2 Answers

Greg Kaleka
Greg Kaleka
39,021 Points

Hey Dave,

You're close, but you're correctly looping through each word (by using astring.split()), but then you're counting occurrences in the string itself, rather than in the list of words. This is a problem for the word "am", which is found twice in the string itself (s*am, **am*). Make sure you're counting words, not character strings.

Let me know if you figure it out!

Cheers :beers:

-Greg

Ahhh, makes total sense now. Thanks for explaining that!

Manish Giri
Manish Giri
16,266 Points

This worked for me -


Mod Edit

Removed answer with no explanation.

Greg Kaleka
Greg Kaleka
39,021 Points

Hi Manish,

Please don't post solutions with no explanation. Ideally, answers should point the student in the right direction from where their code is now, without even actually giving the answer away. Explanations and hints vs posting the solution.

Feel free to edit your answer and provide Dave with some help that still lets him learn :blush:

Best,

-Greg