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

Question about implementing function word_count

Im not sure why my code is not being accepted. This is the result for when i pass the example parameter into the function:

word_count("I do not like it Sam I Am")

{'i': 2, 'do': 1, 'not': 1, 'like': 1, 'it': 1, 'sam': 1, 'am': 1

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):
    string = string.lower() 
    string = string.split(' ')
    dictionary = {}
    for word in string:
        x = string.count(word)
        dictionary.update({word: x})
    return dictionary
Chris Jones
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Chris Jones
Java Web Development Techdegree Graduate 23,933 Points

That's weird. I tried something similar and it worked in the Python shell, but didn't work in the quiz. Maybe try contacting Support? I started at Treehouse with Python and I think I remember the quiz questions being very picky....

def word_count(string):
    d = {}
    string = string.lower();
    word_list = string.split(' ')

    for word in word_list:
        d[word] = word_list.count(word)
    return d
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> d = {}
>>> d
{}
>>> string = 'I do not like it Sam I Am'
>>> string
'I do not like it Sam I Am'
>>> string.lower()
'i do not like it sam i am'
>>> string = string.lower()
>>> string
'i do not like it sam i am'
>>> d
{}
>>> string
'i do not like it sam i am'
>>> word_list = string.split(' ')
>>> word_list
['i', 'do', 'not', 'like', 'it', 'sam', 'i', 'am']
>>> for word in word_list:
    d[word] = word_list.count(word)


>>> d
{'it': 1, 'do': 1, 'like': 1, 'i': 2, 'not': 1, 'am': 1, 'sam': 1}
>>> 

2 Answers

Stuart Wright
Stuart Wright
41,118 Points

The problem is that you need to split on all whitespace rather than simply ' ', as there are different types of whitespace characters. So just use .split() without any argument, since all whitespace characters is the default.

It's picky for sure, but it's what you need to do to pass the challenge.

Thanks guys!