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

Python Collections. Dictionaries. Word Count Challenge. The correct solution does not pass

I guess this might be not the cleanest solution. Still it's correct. And it doesn't pass. Any mistakes or improvements?

def word_count (s): s1 = s.lower() arr = s1.split(' ') dcn = {} for i in arr: if i in dcn: dcn[i] += 1 dcn.update({i: dcn[i]}) else: ctn = 1 dcn.update({i: ctn}) return dcn

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 (s):
    s1 = s.lower()
    arr = s1.split(' ')
    dcn = {}
    for i in arr:
        if i in dcn:
            dcn[i] += 1
            dcn.update({i: dcn[i]})
        else:
            ctn = 1
            dcn.update({i: ctn})
    return dcn

2 Answers

Stuart Wright
Stuart Wright
41,120 Points

The challenge is being a little picky, but it's this line that's causing it to fail:

    arr = s1.split(' ')

Just change it to this to pass the challenge:

    arr = s1.split()

This is because by default the split() method splits on all whitespace characters, but when you pass ' ' to it, it only splits on a regular space character (there are other types of whitespace characters such as tabs for example).

As for the rest of your code, if I was to suggest one improvement it would be to use more descriptive variable names. I always find that makes code easier to follow.

James Peter
James Peter
3,180 Points

Python Collection: Dictionaries - word_count challenge

Was struck with the same.

Was able to complete the challenge by changing it to .split() Thanks Stuart.

Thanks, Stuart! That solves it