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

Not understanding code 100%, Just need some minor clarification :)

The following code solved a code challenge, I get it for the most part as i got help from others. But what i dont understand is the usage for "count", and the else: Word_dict[letter] = 1, is that just keeping it as is, if so, why have it there. Anyone who can go through the code and explain it would be a great help!!!

def word_count(string):

    new_string = string.lower()
    wordlist = new_string.split()
    count = 0
    word_dict = {}

    for letter in wordlist:
        if letter in word_dict:
            count += 1
            word_dict[letter] += 1
        else:
            word_dict[letter] = 1
    return word_dict

1 Answer

Ismail KOÇ
Ismail KOÇ
1,748 Points

new_string value not used in for loop so:

    new_string = string.lower()
    wordlist = new_string.split()
    count = 0
    word_dict = {}

    for letter in wordlist:
# easy way:
    word_dict = {}
    for letter in string.lower().split():

and you do not need count value. In summary we can write this:

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