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

Spencer Hill
Spencer Hill
1,397 Points

My code works in workspaces but the challenge doesn't accept it.

My code returns the values requested by the challenge in workspaces but it's not accepted by the task itself.

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.

word_dict = {}

def word_count(string):
    string_list = str(string).lower().split(" ")

    for word in string_list:
        if word in word_dict:
            old_value = int(word_dict[word])
            word_dict[word] = old_value + 1
        else:
            word_dict[word] = word
            word_dict[word] = 1

    return (word_dict)

2 Answers

Oszkár Fehér
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Oszkár Fehér
Treehouse Project Reviewer

Hi Spencer Belived or not it took me 20 minutes till i figured out why it's not accepted because your code does what it has to do. The split() method by default splits the string at white spaces so you don't need the " ".

str(string).lower().split()

Here is a simplyfied version of your code

def word_count(item):
    word_dict = {}
    for word in item.lower().split():
        if word in word_dict:
            word_dict[word] += 1
        else:
            word_dict[word] = 1

    return word_dict

I hope was for your help Also in the future for good practice try to not name your variables like bulit in methods, sometimes it can couse problem and it's hard to figure out the bug(ex string) Keep up the good work and happy coding

Stuart Wright
Stuart Wright
41,120 Points

The challenge is being a little picky, but it's this line that's causing it to fail:

    string_list = str(string).lower().split(" ")

Just change it to this to pass the challenge:

    string_list = str(string).lower().split()

This is because by default the split() method splits on all whitespace characters, but when you pass " " to it, it only splits on a regular space character (there are other types of whitespace characters such as tabs for example).