Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
218,692 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"))