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

Nyarts Gnaw
Nyarts Gnaw
1,079 Points

Why do I miss words in string when loop this way?

Just as I said in my title, why is that?

word_count.py
# E.g. word_count("I am that I am") gets back a dictionary like:
# {'i': 2, 'am': 2, 'that': 1}
# Lowercase the string to make it easier.
# Using .split() on the sentence will give you a list of words.
# In a for loop of that list, you'll have a word that you can
# check for inclusion in the dict (with "if word in dict"-style syntax).
# Or add it to the dict with something like word_dict[word] = 1.

def word_count(words):
    dict = {}
    test = words[:].split()
    for key in words:
        count = 0
        while True:
            try:
                test.remove(key)
                count += 1
                dict.update({key:count})
            except:
                break
    return dict

2 Answers

Steven Parker
Steven Parker
231,269 Points

For one thing, the argument that you named "words" is actually a string, so when you iterate over it (for key in words:) your key will be just one single letter of the string each time.

You have some other issues too. Why not try using the hints given in the challenge comments? They can help you create a more compact solution, as well as helping resolve some of the issues.

Jon Hockley
Jon Hockley
3,781 Points

Follow the advice given to you in the challenge. You are not using the .split() method on the string as it advises you.

I have run your code and when you use the for loop on the dictionary, each individual character is being assigned to key.

Nyarts Gnaw
Nyarts Gnaw
1,079 Points

Hey man I change my code some and I get the right answers. To be honest I didn't notice the green words and I didn't know about "X in Y " could be used as condition in if. I've changed that in my function

def word_count(words): dict = {} test = words[:].split() for key in words: count = 0 while True: try: test.remove(key) count += 1 dict.update({key:count}) except: break return dict