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

fahad lashari
fahad lashari
7,693 Points

Not sure what is wrong with the code. Help please

Not sure what is wrong with the code. It works perfectly fine when I have tested it and delivers the result no matter what string is passed. Do let me know if you can find an error.

kind regards,

Fahad

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):
    string = string.split()
    dictionary = {}
    for letter in string:
        dictionary[letter] = string.count(letter)
    return dictionary

1 Answer

Umesh Ravji
Umesh Ravji
42,386 Points

Hi Fahad, your just missing the part where you have to lowercase the string (it's in the comment section at the top of the coding area).

def word_count(string):
    string = string.lower().split()  # you could just do it here :)
    dictionary = {}
    for letter in string:
        dictionary[letter] = string.count(letter)
    return dictionary

Just as a side note, you may want to name variables more intuitively. As soon as I started reading the for loop, I saw letter in string. It's not clear at first what that actually means. Consider the code below:

def word_count(string):
    words = string.lower().split()
    dictionary = {}
    for word in words:
        dictionary[word] = string.count(word)
    return dictionary

Also, a different way of writing the function, for performance reasons, you could use:

def word_count(string):
    words = {}
    string = string.lower()
    for word in string.split():
        if word in words:
            words[word] += 1
        else:
            words[word] = 1
    return words