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

My code works in shell, but not on Treehouse

As you can see from the code under, it returns a dictionary exactly like instructed. It works in shell, but not at Treehouse. Could somebody give me a clue?

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(in_arg):

    temp = in_arg.lower()
    words = temp.split(' ')

    out_dict = {}

    for word in words:
        count = 1
        if word in out_dict:
            count = out_dict[word] + 1
            out_dict.update({word: count})

        elif word not in out_dict:
            out_dict.update({word: count})

    return out_dict

1 Answer

Hi there!

Don't worry, you got it - great job!

The catch on this (that comes up ALL the time) is that you have to split on all whitespace not just spaces. Just change your split method call from split(" ") to split()

For example, with split(" "):

>>>print(word_count("I do not like it sam\ni am"))
{'i': 1, 'do': 1, 'not': 1, 'like': 1, 'it': 1, 'sam\ni': 1, 'am': 1}

And with split():

>>>print(word_count("I do not like it sam\ni am"))
{'i': 2, 'do': 1, 'not': 1, 'like': 1, 'it': 1, 'sam': 1, 'am': 1}

Hope it helps - good job :) Jon