Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (Retired) Dictionaries Word Count

Fareez Ahmed
Fareez Ahmed
12,728 Points

split_string not defined? What's wrong here? stuck!

def word_count(a_string): split_string = a_string.split() string_dict = {} for word in split_string: if word in string_dict[word]: string_dict[word] += 1 else: string_dict[word] = 1

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(a_string):
  split_string = a_string.split()
  string_dict = {}
for word in split_string:
    if word in string_dict[word]:
        string_dict[word] += 1
    else:
        string_dict[word] = 1

2 Answers

Paul Bentham
Paul Bentham
24,090 Points

OK I didn't immediately know how to do this but after a little searching and seeing one of Kenneths answers on another post:

Try this (see comments in the code to help):

def word_count(a_string):
  split_string = a_string.split()
  string_dict = {}
  #first populate the dictionary with the keys being each word in the string, all having zero for their values.
  for item in split_string:
    string_dict[item] = 0

  #Then cycle through the split string again and if the word is one of the keys in the dictionary add 1 each time.
  for item in split_string:
    if item in string_dict.keys():
        string_dict[item] += 1

  return string_dict        

print word_count('this is this my string')
Fareez Ahmed
Fareez Ahmed
12,728 Points

I see, thanks... so basically I didn't initialize the string items to zero in the dictionary