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

Thompson Pham
Thompson Pham
5,625 Points

I don't understand why my code is not working here, I even ran it on a python testing site and it worked there.

I take a string that is passed into the function, I split the string on single white spaces into a list, I loop through the list and lower case each string in the list, I run a loop to see if there are repeats in the dictionary that I am building, then I update the dictionary with the word as well as the count. I then return the dictionary.

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(string):
    string_list = string.split(" ")
    string_dict = {}
    for word in string_list:
        i = 1
        word = word.lower()
        for repeat_word in string_dict.keys():
            if repeat_word == word:
                i += 1
        string_dict.update({word:i})
    return string_dict

2 Answers

Oskar Lundberg
Oskar Lundberg
9,534 Points

Hey there! I'm not gonna be able to tell you why your code doesn't pass the challenge since it seems to me that it should. I tried the challenge myself and the code I wrote failed this time, even though it seems like it should work. I will post both my solution that failed and my old solution I made a while ago (which passes the challenge)

What I wrote just now (which weirdly failes):

def word_count(string):
    string = string.lower()
    string_list = string.split(" ")
    string_dict = {}
    for word in string_list:
        word_count = string_list.count(word)
        string_dict.update({word: word_count})  
    return string_dict

What I wrote back when I did the challenge (This works!):

def word_count(string):
    dictionary = {}
    list_of_the_words = string.lower().split()
    for word in list_of_the_words:
        if word not in dictionary:
            dictionary[word] = 1
        else:
            dictionary[word] += 1
    return dictionary

I'm gonna go ahead and guess that the tests that have been written for this challenge aren't flawless, and that's why your solution doesn't work here. Hope this helps :D

See the answer here for an explanation