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 (2016, retired 2019) Dictionaries Word Count

Abrar Fahim
Abrar Fahim
1,071 Points

I have no idea what to do please help

I don't get the question and don't know what to do. I checked some of the solutions and they kept on putting this:

 if word in dict:
            dict[word] += 1
        else:
            dict[word] = 1

what does that even mean? can somebody explain and help me and also why do I need a for loop?

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(word):
    word
Ted Runyon
Ted Runyon
1,773 Points

First you will want to make your string argument lowercase:

def word_count(s):
    list_of_lowercase_words = s.lower()

Then you can split the string and store that in the same variable:

def word_count(s):
    list_of_lowercase_words = s.lower().split() 

Then create an empty dictionary:

dictionary_of_words = {}

Then you want to create a for loop because you need to iterate through the string(which was turned into a list during, the split() method). Basically your string is now a list of words and you need a for loop to go through each word. Here we can iterate through each word in our list and count them.

for word in list_of_lowercase_words:
    try:
        dictionary_of_words[word] += 1
    except KeyError:
        dictionary_of_words[word] = 1

Finally returning the dictionary:

return dictionary_of_words

code put together looks like this.

def word_count(s):
    list_of_lowercase_words = s.lower().split()
    dictionary_of_words = {}

    for word in list_of_lowercase_words:
        try:
            dictionary_of_words[word] += 1
        except KeyError:
            dictionary_of_words[word] = 1

    return dictionary_of_words

This is my first time posting on here and I was stuck on this for a little while. I know how it feels. Hope this helps!

1 Answer