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

Different ways to solve the problem

Alright, I am having some difficulty getting this problem to be passed.

The challenge problems do give you a good understanding of things, however I believe that you are looking for a certain way to do this.

This is where I believe that my problem is lying.

Here is a copy of my code that I used in workspace to test the function to ensure it works:

sent = "I am that I am"
sent = sent.lower().split()
sent_dict = {}

for x in range(0, len(sent)):
  if (sent[x] in sent_dict):
    #value = sent_dict[sent[x]] + 1
    sent_dict.update({sent[x] : sent_dict[sent[x]] + 1})
  else:
    sent_dict.update({sent[x] : 1})
print(sent_dict)

This gives me the result: {'that' : 1, 'am' : 2, 'i' : 2}

This is the correct output that I was looking for in my code.

Here is a copy of my code I put in the challenge portion:

def word_count(string):
  string = string.lower().split()
  dictionary = {}

for x in range(0, len(string)):
  if (string[x] in dictionary):
    dictionary.update({string[x] : dictionary[string[x]] + 1})
  else:
    dictionary.update({string[x] : 1})
return dictionary

Is there something that I am missing?

I did find the other way in which you wanted to the for loop to be done.

I changed the for x in range... line so that it would pass the challenge

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Well, your code looks like it has some indentation issues. Doing a for loop until len(string) is going to go one number too high, since the len and the indexes are one different (indexes start at 0, len starts at 1). This is a big reason why Python uses something like for word in string: since string is already a list.

ifs don't need parentheses. They shouldn't break anything here but it's a good idea to avoid unnecessary punctuation, especially if it can cause an issue.

Why are you using .update() when you're only updating one key? It works but it's way more code than you need.

I think the reason that I am doing the parentheses is a habit from c and c++. As for the .update() was to remain more consistent, in my eyes, due to declaring an empty dictionary prior. I will definitely take a look at the other way to update just one key at a time.