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 Stage 3 Challenge 1

Create a function named word_count() that takes a string. Return a dictionary with each word in the string as the key and the number of times it appears as the value.

def word_count(a_string):

  a_string = {"I am that I am"}

  for split_string in a_string.split():

    return split_string

This is what I have so far..need help..

3 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

OK, so you've split the string up into words. Your a_string.split() gives you ['I', 'am', 'that', 'I', 'am'].

Now, how would you loop over that and keep a count of each time each word appears? Since each thing in that list is a string, it might make sense to turn them into keys in a dictionary. That way the value could be the number of times it appears.

How would you go about doing it that way?

def word_count(a_string):

  a_string = {"I am that I am"}

  for split_string in a_string.split():

    if word in a_string.split():

      count += 1

    return a_string.split()

Am I way off? Or close...?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Well, getting closer. Let me show you how I'd start it:

def word_count(a_string):
    counts = {}
    for word in a_string.split():

Now I need to check if word is in counts. If it is, I need to bump up its value by 1. If it's not, I need to add it and set the value to 1.

Then, finally, I need to return counts at the end.

See what you can get from that.

def word_count(a_string):

counts = {}

for word in a_string.split():

  if word in counts:

    word += 1

  else:

    word + 1 = counts

return counts

I hope it got closer.

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Getting really close. How do you assign keys in a dictionary, though?

counts[word] would be the reference to the word key in the dict. word += 1 tries to add 1 to the word, which is a string. That'll blow up.

And word + 1 = counts doesn't make sense because you're doing an assignment into a math operation. Again, you'll want to get the counts[word] key and then set it to 1.