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

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