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

Create a function named word_count() that takes a string. Return a dictionary with each word in the string as the key an

Guys, need help with the code. Not sure what I am doing wrong.

my_string = "I am here you are there I you you"

def word_count(my_string):
  string_lowercase =  my_string.lower()
  string_split = string_lowercase.split()
  my_dict = {}

  for word in string_split:
      if word in string_split:
        my_dict[word] = 1
      else:
        my_dict[word] += 1
  return my_dict

[MOD: added ```python formatting -cf]

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

Your code is very close! In detecting if the word has been seen you need to fixed to things: search the keys of my_dict instead of string_split and reverse the conditions so that you initialize the count to 1 if not in string_split:

def word_count(my_string):
  string_lowercase =  my_string.lower()
  string_split = string_lowercase.split()
  my_dict = {}

  for word in string_split:
      if word not in my_dict:  # <-- corrected this line.
        my_dict[word] = 1
      else:
        my_dict[word] += 1
  return my_dict

You could simplify it a bit with:

def word_count(my_string):
    my_dict = {}
    for word in my_string.lower().split():
        if word in my_dict:
            my_dict[word] += 1
        else:
            my_dict[word] = 1
    return my_dict

Chris, thanks for your help.