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

parth bhardwaj
parth bhardwaj
4,353 Points

Bummer! Hmm, didn't get the expected output. Be sure you're not splitting only on spaces!

My code runs on other editors, here it is showing an error

# 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.
import re
def word_count(a):
    x=re.findall(r"[\w']+", a)
    for word in x:
        for repword in x:
            if word==repword:

    return dict1

Hi parth,

Please be patient and give others a chance to answer your question instead of posting the same question again. If you wanted to add another attempt, you can edit your original question and add your code to that one.

Also, you can search the community and see if others have had your same question.

Steven Parker
Steven Parker
230,230 Points

I assume Jason is referring to this question, although the code in it is quite different.

1 Answer

You don't need a Regex expression. The split function splits on all whitespace.


>>> 'Alex likes programming'.split()
['Alex', 'likes', 'programming']

So, to solve this, you can do this:

def word_count(a):
    words = a.lower().split()
    result = {}
    for word in words:
            result[word] += 1
        except KeyError:
            result[word] = 1
    return result

I hope this helps. ~Alex