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

Gary Law
Gary Law
14,632 Points

Cannot pass Python stage 3 - Dictionaries Challenge Task 1

I dont know why the following code not working? Anyone can help? Thanks a lot.

def word_count(my_string):
  my_dict = {}
  my_list = my_string.lower().split()
  for item in my_list:
    if item in my_dict:
      my_dict[item] = my_dict[item] +1
    else:
      my_dict[item] = 1
Kenneth Love
Kenneth Love
Treehouse Guest Teacher

The only problem with your code is that you didn't return my_dict at the end.

But I see a place where I need to improve the code challenge, so thanks! (check your badges for something special)

Gary Law
Gary Law
14,632 Points

Thanks Kenneth!

1 Answer

Chris Shaw
Chris Shaw
26,676 Points

Hi Gary,

I've outlined a couple of points below.

  1. You can use the increment operator to increase the number count for the dictionary key
  2. You aren't returning your dictionary once the for loop has being completed.

I've slightly modified your code just to make it clearer what's happening.

def word_count(words):
  my_dict = {}
  words = words.lower()

  for word in words.split():
    if word in my_dict:
      my_dict[word] += 1
    else:
      my_dict[word] = 1

  return my_dict
Gary Law
Gary Law
14,632 Points

Hi Chris, thanks so much for your help!