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

Everett Yates
Everett Yates
9,280 Points

I'm so lost, can someone help me?

I can't seem to figure out what I'm missing.

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(str):
    count_dict = {}
    for words in str.lower().split():
        count_dict[words] = str.count(words)
    return count_dict

2 Answers

This should work:

def word_count(str):
    listitem=str.lower().strip().split()
    dicti={}
    for item in listitem:
        dicti[item]=listitem.count(item)
    return dicti

sorry for the formatting (basically didn't read the Markdown cheatsheet), but if you format it right, it should work ;)

Hi Everett

Basically, lowercase the string and split on whitespace, create a dictionary and check if each word appears in that dictionary, if it does add it to the count. See below example

def word_count(mystring):
    words = mystring.lower().split()
    mydict = {}
    count = 1
    for word in words:
        if word in mydict:
            mydict[word]=count+1
        else:
            mydict[word]=count
    return mydict
Everett Yates
Everett Yates
9,280 Points

hmm, your solution didn't seem to work.

there is nothing wrong with my code, i ran it locally and it gives me exactly what's being asked. Will check, could be something to do with the code challenge interpreter itself. Will get back to you.

sorry just realised my logic was off slightly. It can also be done like so.

def word_count(mystring):
    words = mystring.lower().strip().split()
    mydict = {}
    for word in words:
        if word in mydict:
            mydict[word]=mydict[word]+1
        else:
            mydict[word]= 1
    return mydict