Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!