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

Mattan Yedidya
Mattan Yedidya
1,084 Points

Is the problem that I am trying to create a key off of a value that may not exist? Thanks!

Need help pls!

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.list()
    temp = {}
    for item in string_list:
        temp[item] = temp[item] + 1
Bapi Roy
Bapi Roy
14,237 Points
def word_count(str):
    temp_dict = {}
    str_list = str.lower().split(" ")

    for i in  str_list:
        if i  in temp_dict:
            temp_dict[i] = temp_dict[i] + 1
        else:
            temp_dict[i] =  1

    return temp_dict

try this

1 Answer

You have to use split function() over the string. Split(arg) function splits the string on the basis of 'arg' passed into it.

Remember... Don't pass any arguments in split().[by default, if not specified argument is space.]

# 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):
    words = string.lower().split()
    res = {}
    for word in words:
        if word in res.keys():
            res[word] += 1
        else:
            res[word] = 1
    return res