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

Alex Espinosa
Alex Espinosa
3,226 Points

The error handler can't see word_count() but I can't see why

I think this may have to do with declaration of my_dict

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.

def word_count(my_string):
  my_list = my_string.lower().split(" ")

  for item in my_list:
    if item not in my_dict:
      my_dict[item] = my_list.count(item)

  return my_dict

2 Answers

David Axelrod
David Axelrod
36,073 Points

Yup! You've gotta create the string dict before everything else. then go through each item in the string and then if the word has appeared before, increment it's count. otherwise start a count for that word.

BOOM, you're done!!

def word_count(the_string):
  string_dict = {}
  for word in the_string.split():
    if word in string_dict:
        string_dict[word] += 1
    else:
        string_dict[word] = 1
  return string_dict
Jaime Lossada
Jaime Lossada
3,721 Points

Alex, you need pass in the dictionary to the function before you can use it. Or create it inside the function, depending on your need. But right now you are trying to access my_dict in the if statement without having any reference to my_dict