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

X TAO-COLLINS
X TAO-COLLINS
4,922 Points

word_count

def word_count(str): return dict(Counter(str.lower().split()))

word_count("I do not like it Sam I Am") {'i': 2, 'do': 1, 'not': 1, 'like': 1, 'it': 1, 'sam': 1, 'am': 1}

I have successfully ran through this in Python 3.6.1 Shell.

It gives the correct answer as required, I don't understand what's wrong? Help needed ASAP

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.
from collection import Counter

def word_count(str):
    return dict(Counter(str.lower().split()))

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

New idea: try changing str to string.

X TAO-COLLINS
X TAO-COLLINS
4,922 Points

I have changed the str into string, still not working. :(

2 Answers

X TAO-COLLINS
X TAO-COLLINS
4,922 Points

I have tried a different method, less straight-forward than the previous one I posted above. I took the reference from https://www.pythonlearn.com/html-008/cfbook010.html

def word_count(str): d=dict() for x in str.lower().split(): if x not in d: d[x]=1 else: d[x]=d[x]+1 return d

word_count("I do not like it Sam I Am") {'i': 2, 'do': 1, 'not': 1, 'like': 1, 'it': 1, 'sam': 1, 'am': 1}

I copied the code you posted originally and replaced str with string and it worked for me! Try closing and reopening your window?