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

A question in the word count exercise

You can see the question written in the comment in the code, but to summarize.

My code as far as making split words as key and the count number of the word as values in the new dictionary works.

The issue is even though I used a for loop it only takes one of the split item, not all of the items.

I tried using while loop only to find the same result.

Why is it doing this? Thank you in advance.

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):
    x = list(string.lower().split())
    for items in x:
        new_dict = dict([[items, x.count(items)]])  
    return new_dict 

# when I tried this code with a string value ("I do not like it Sam I Am") on eclipe 
# with return replaced with print function
word_count("I do not like it Sam I Am")
# the new_dict comes out to be just this {"am": 1}
# It does not include all the splitted items in the list x.

# Why is it only giving me one of the splitted item, when I used a for loop?
# Since I used a for loop I expected that the loop was going to continue 
# until every split item was included..
# What am I doing wrong?

1 Answer

Hi there!

Your for loop is making a new dictionary each time, not adding a new item to the dictionary, so when you get to the end of the loop, there's only one item in the dictionary as each other iteration has written over new_dict with a different dictionary.

Also beware of using count for this. count() returns the number of times a substring appears in a given string, not the number of times a word appears. For example, the word "i" will appear in "we rolled down the hills again and again" 3 times according to count :)

Hope it helps!