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 (2016, retired 2019) Dictionaries Word Count

andrew falcone
andrew falcone
8,651 Points

word_count dictionary question code seems to work but my solutions is not being accepted :(

I think my code is right, but it isn't being accepted with no information about what is wrong! (WTF, why not give error message?)

wordcount.py
# E.g. word_count("I do not like it Sam I Am") gets back a dictionary like:
# {'i': 2, 'do': 1, 'it': 1, 'sam': 1, 'like': 1, 'not': 1, 'am': 1}
# Lowercase the string to make it easier.



def word_count(string):
  string_array = my_string.split(" ")
  word_dictionary = {}
  for word in string_array:
    lower_word = word.lower()
    try:
      word_dictionary[lower_word] += 1
    except:
      word_dictionary[lower_word] = 1


  return word_dictionary

If you click on the topic path above (in this case Word Count)

Python > Python Collections > Dictionaries > Word Count

you can see how others have solved the same challenge

2 Answers

The other has to do with splitting on all whitespace

split(" ") will split on blank spaces only

split() includes tabs, and others

If you paste this into a workspace you'll see a better error message.

NameError: name 'my_string' is not defined

You have 'string' as a parameter but split 'my_string'.

andrew falcone
andrew falcone
8,651 Points

I just fixed that (that's annoying that python doesn't give you an error message for trying to use a variable defined outside the scope of the function!).

I changed my_string to string and it is not giving an error message but still won't accept my answer :(

andrew falcone
andrew falcone
8,651 Points

Also, is there a place to see best solutions for problems like this? I have no idea if the way I solve a problem is the most efficient way or best practice.

Thanks!