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

Paul Heneghan
Paul Heneghan
14,380 Points

REALLY stuck incrementing the word count in the dict, tried int() and then add 1. Don't know how to combine w/ .update

The added code works in workspace, the print shows that it's finding the multiple uses of the words. Thanks for any help!

word_count.py
# E.g. word_count("I am that I am") gets back a dictionary like:
# {'i': 2, 'am': 2, 'that': 1}
# Lowercase the string to make it easier.
# Using .split() on the sentence will give you a list of words.
# In a for loop of that list, you'll have a word that you can
# check for inclusion in the dict (with "if word in dict"-style syntax).
# Or add it to the dict with something like word_dict[word] = 1.
Paul Heneghan
Paul Heneghan
14,380 Points

myString = "I am what I am" myDict = {}

def word_count(myString): myList = (myString.lower()).split(" ") for i in range(len(myList)): if myList[i] in myDict: #add 1 to word count of word print("{} already in myDict".format(myList[i]))
else: #add i to myDict with number count as 1 myDict.update({myList[i]: '1'}) print(myList)

2 Answers

Steven Parker
Steven Parker
229,732 Points

It's hard to read Python without the code markdown, but if I'm interpreting it correctly...

:point_right: You have a few separate issues here:

  • the challenge wants you to return a dictionary, you won't need to print anything
  • you might want to store your counts as numbers instead of strings
  • if a word is already in the dictionary, you will want to increase the count
Paul Heneghan
Paul Heneghan
14,380 Points

Thanks, Steven. I understand what you're saying. I'm close now, my count is off if I go above two occurrences, I suspect it's the placement in the loop and am testing that now. I appreciate the help!