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 (Retired) Dictionaries Word Count

Rodrigue Loredon
Rodrigue Loredon
1,338 Points

Please help with python script "word_count.py" dealing with dictionnaries.

The challenge is: Create a function named word_count() that takes a string. Return a dictionary with each word in the string as the key and the number of times it appears as the value.

My script doesn't work, it just fails

word_count.py
aString = "I am that I am"


def word_count(aString):

  aDict = {}

  count = 1

  aSplitString = aString.lower().split()

  for word in aSplitString:

    if word not in aDict:

      aDict = aDict.update({word:count})

    else:
        aDict = aDict.update({word:count+1})

    continue

return aDict


word_count(aString)

2 Answers

Dan Johnson
Dan Johnson
40,532 Points

The challenge will handle all the input and function calling for you so you won't need to worry about that. Here's some changes you can make:

def word_count(aString):
  aDict = {}
  # count isn't required anymore.

  aSplitString = aString.lower().split()

  for word in aSplitString:
    if word not in aDict:
       # Instead of update we can just assign 1 to any new key
       aDict[word] = 1
    else:
       aDict[word] = aDict[word] + 1
    # continue is not needed at the end of a loop. It's the
    # default behavior.

  # Watch for indentation
  return aDict