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

Rodrigue Loredon
Rodrigue Loredon
1,338 Points

Help with word_count.py

Can someone tell me with my code is not working? I always get back an empty dictionnary.

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.
aString = "I am that I am"
aDict = {}

def word_count(aString):

  count = 1

  aSplitString = aString.lower().split()

  for word in aSplitString:

    if word not in aDict:

      aDict.update({word:count})

    else:

        aDict.update({word:count+1})

    continue
  return aDict

4 Answers

Rodrigue Loredon
Rodrigue Loredon
1,338 Points

Thank you for you help. I was able to solve my problem. I wrote the function this way:

def string_factory(dicts,string):

  final_list = []

  for item in dicts:

    newString = string.format(name='name',food='food')

    final_list.append(newString)

  return final_list

Take care

Gina Scalpone
Gina Scalpone
21,330 Points

I was able to run your code, so I'm not sure what the problem was, but I also rewrote it using a more common method:

a_dict = {}

def word_count(a_string):
    a_split_string = a_string.lower().split()
    print(a_split_string)

    for word in a_split_string:
        print(word)
        if word in a_dict:
            a_dict[word]=a_dict[word]+1

        else:
            a_dict[word]=1

    return a_dict

word_count("I am that I am")

print(a_dict)
Gina Scalpone
Gina Scalpone
21,330 Points

You need to call the function for the dictionary to be updated.

Rodrigue Loredon
Rodrigue Loredon
1,338 Points

Hello Gina, I tried to call the function at the end of the script but that didn't work for me.

Gina Scalpone
Gina Scalpone
21,330 Points

Did you call it with the aString as an argument? The function needs an argument to work, so just calling word_count() won't work, you need to call word_count(aString).

Rodrigue Loredon
Rodrigue Loredon
1,338 Points

Thanks for your help and insight it was much appreciated!