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

Caleb Shook
Caleb Shook
3,194 Points

I wrote this in Workspaces and it worked perfectly...

In Workspaces, this worked fine but after copy and pasting it into the challenge and fixing the indentation errors it doesn't pass. I get an error saying that I didn't lowercase the string, but I did and tested that as well.

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):
    words = {}
    word = ""
    end = len(string)
    pos = 0
    for letters in string.lower():
        pos+= 1
        if letters!= ' ' and pos != end:
            word += letters.lower()
        elif pos == end:
            word+= letters.lower()
        if word in words:
            words[word] += 1
            word = "" 
            continue
        elif word in words:
            words[word] += 1
            word = ""
            continue
        else:
            words.update({word:1})
            word = ""
            continue
    return words

2 Answers

james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

this code returns a dict of the counts of every letter in the string, not every word. look at the split method to break the string of words into a list of words, and count those up and return a dict of that.

Caleb Shook
Caleb Shook
3,194 Points

I am not sure I understand. When I run it, I get back a dict of words with how many times they have occurred.

Caleb Shook
Caleb Shook
3,194 Points

I redid the code but it is still failing.

def word_count(string):
    words = string.lower().split(' ')
    wordCount = dict()
    for word in words:
        if word in wordCount:
            wordCount[word] += 1
        else:
            wordCount.update({word:1})
    return wordCount ```