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

Hey there, my attempted solution for this problem ```word_count("I do not like it Sam I Am")``` failed please advise

I have tried testing out my solution in many other apps and it works flawlessly. I am not sure what I am missing in my function

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):
    lower_string = string.lower()
    string_list = lower_string.split(" ")

    final = {}
    count = 1
    for word in string_list:
        if word in final.keys():
            final[word] =  count + 1
        else:
            final[word] =  count

    return final

2 Answers

Steven Parker
Steven Parker
231,236 Points

Perhaps you're testing with "lucky" data. The "Bummer" message gave you a hint: "Be sure you're lowercasing the string and splitting on all whitespace!" To split on "all whitespace" the argument to "split" should be left empty or set to None.

Also, it looks like "count" will continue to grow as the loop runs, but a new entry should always have the value set to 1, and an existing one should be incremented by one from its own current value.

Thanks, Steven but I have tried to make some modifications but it still fails

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

    final = {}
    count = 1
    for word in string_list:
        if word in final.keys():
            final[word] =  final[word] + 1
        else:
            final[word] =  1

    return final


print(word_count("I do not like it Sam I Am"))

Thanks, Steven I have solved it

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

    final = {}
    count = 1
    for word in string_list:
        if word in final.keys():
            final[word] =  final[word] + 1
        else:
            final[word] =  1

    return final


print(word_count("I do not like it Sam I Am"))