Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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