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 (Retired) Dictionaries Word Count

Nyarts Gnaw
Nyarts Gnaw
1,079 Points

Why it keep saying I miss some words from the string?

As described in title

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[:]
    for key in words:
        count = 0
        while True:

            try:
                test.remove(key)
                count += 1
                dict.update({key:count})
            except:
                break

    return dict

1 Answer

Steven Parker
Steven Parker
216,083 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.

Nyarts Gnaw
Nyarts Gnaw
1,079 Points

It's fixed after I add .split() into my code, although It works perfectly right now. And I didn't notice the green words before.... Well I will try guide from green words, but before that I don't get what you mean about "other issues", I'm not quite clear about the loop that : now in my code, I .remove key from test, a copy of the input words, and it looks work perfectly. Could you be clear of the possible problem?