Python Python Collections (2016, retired 2019) Dictionaries Word Count

Todd Teese
Todd Teese
22,679 Points

I have the correct output, is there anything else to this?

I've tried this in a separate sandbox, and I'm getting the correct output dict, with words for keys and int's for values. Just wondering if there's something I'm doing wrong or weird in this code challenge.

Thanks in advance!

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(inputString):
    wordList = inputString.lower().split(" ")
    wordDict = dict()
    for word in wordList:
      if wordDict.has_key(word):
        wordDict[word] = wordDict[word] + 1
      else:
        wordDict[word] = 1
    return wordDict

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 56,839 Points

You are on the right path. Two errors to correct:

  • dict object wordDict has no attribute has_key. Instead use:
if word in wordDict.keys():
# or the sort version
if word in wordDict:  # .keys() is assumed
  • The split should be on whitespace not a literal " " (space). No argument means split on whitespace.

Post back if you need more help. Good luck!

Todd Teese
Todd Teese
22,679 Points

Awesome, thanks for the help!