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

I have tested the following code and I am getting the exact result as what is in the comment.

I am getting the exact same result as in the comment on the page. Here is my code:

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.split()

lower_case_words = [] 

for word in words:
     lower_case_words.append(word.lower())  

dictionary = {} 

for word in lower_case_words:
    if dictionary.has_key(word):
        dictionary[word] += 1 
    else:
        dictionary[word] = 1 
return dictionary

1 Answer

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Samiul,

First, please consider properly formatting your code snippets at code, so that it is possible to copy-paste your code into another editor. As explained in the Markdown Cheatsheet underneath the text box, you should put three backticks then the language name before your code snippet and three backticks after. You can then click the preview button in the bottom right of the text box to confirm that your code is properly formatted before submitting your post. If you do this correctly, your code will look like this:

def word_count(string):

    words = string.split()

    lower_case_words = [] 

    for word in words:
        lower_case_words.append(word.lower())

    dictionary = {} 

    for word in lower_case_words:
        if dictionary.has_key(word):
            dictionary[word] += 1 
        else:
            dictionary[word] = 1 
    return dictionary

The first error when running your code is a tab/spaces mismatch. It's impossible to tell whether this is due to incorrectly applying markdown or whether it is code in your original source. If it is the latter, make sure you are consistent and only use spaces or tabs, never mix them.

The other error is your use of the has_key method. This is no longer valid syntax in Python 3. You should use the in keyword instead:

if word in dictionary:

Then your code will pass the challenge

Cheers

Alex