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

Why is this python code saying that it's not defined?

I've had a play around with it and I've put the b = string outside of the func and not in the arguement as a string as I was getting another error message when it was a local variable. please can you tell me what is wrong with this code? It says My_list is not defined.

# 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.
b = ("I am that I am")

def word_count(b):
  my_dict = {}
  My_list = b.split()

  for each_item in My_list:
    my_dict[each_item] = 0

  for each_item in My_list:
    if each_item in My_list.keys():
      my_dict[each_item] += 1

  return my_dict

2 Answers

Chris Adamson
Chris Adamson
132,143 Points

The issue with your code segment is that my_dict is declared inside the word_count method and then your trying to access it outside the method, where it doesn't have scope.

def word_count(b):
  word_list = b.split()
  ret_val = {}
  for word in word_list:
    if word in ret_val:
      ret_val[word] += 1
      ret_val[word] = 1

  return ret_val

my_dict = word_count("a b c")

Thanks again chris but I'm now getting "key error "I"" .