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

Create a function named word_count() that takes a string.

I've been looking at code for so long I'm blocking out on what's wrong with my code.

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(string):
    my_dict ={}
    x = string.lower().split()
    for item in x:
        my_dict[item] = 1
        if item in my_dict:
            my_dict[item] +=1

    return my_dict

5 Answers

my_dict[item] = 1
if item in my_dict:
  my_dict[item] +=1

because of these lines, my_dict[item] =1 comes first will always set the value lookup to 1, EVEN if the key already in the dictionary.

you should do

if item in my_dict:
  my_dict[item] +=1
else:
  my_dict[item] = 1

I was able to pass the challenge with this code:

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

Hope that helps.

Cheers!

Source

I knew it was in there somewhere. Thank you.

def word_count(a_string): string_dict = {} for word in a_string.split(): if word in string_dict: string_dict[word] += 1 else: string_dict[word] = 1 return string_dict Here is your answer again, just to make sure!

Here's my attempt. The output I get for the string "blah blah blah yeah" is {blah: 3, yeah: 4}. It seems that the variable 'count' is continuing its iteration for the next word in my list. Is there another way to have separate iterators for each word in the list, or is Colin's solution the only way to do this?

def word_count(string):
  list_string = string.split()
  my_dict = {}
  count = 0

  for words in list_string:   
    my_dict.update({words: count})
    if words in my_dict:
      count += 1
    else:
      count = 1

    my_dict.update({words: count})


  return print(my_dict)
            ```