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

Justin M
Justin M
1,708 Points

why doesn't this return my dictionary?

fishing for insight

i used regex instead of splitting the string because i just learned it and its more comfortable to work with for the moment. i had a + instead of an * in my findall() but it didn't catch the word "a" until i switched. a little fuzzy on why "a" is not " at least 1 " instance of a word char.

it tells me "bummer" and to make sure i lowercased and split on whitespaces.

when i run this in my python shell or atom runner, everything works perfectly.

these are what i tested it with: word_count("hello my baby hello my honey hello my ragtime gal")

word_count("tHis is a tesT,. and ,STuff A ,iS, test")

word_count("What is up with this stuff? What is up with anything? pants.")

whats up with this stuff? ha. thanks.

wordcount.py
import re

def word_count(string):
    word_list = []
    word_list = re.findall(r'[\w]*[^\W]', string)
    dct = {}
    for word in word_list:
        word = word.lower()
        if word in dct:
            count = dct[word] + 1
            dct.update({word: count})
        else:
            dct.update({word: 1})

    return dct


# 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.

1 Answer

Steven Parker
Steven Parker
231,007 Points

That "Bummer" message contained a hint that you should "split on whitespaces". Your regex carefully excludes punctuation and other "non-word" characters, but a simple split on white space would not. So while your approach may be more elegant, it may not be what the checker is expecting to see.

So split the simple way and you'll pass the challenge.