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


anyone please explain me how every line of this working

# 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(a_string):
    # Convert 'a_string' into lower case and break it up into a list
    words = a_string.lower().split()
    # Declare an empty dictionary, ready to be populated
    dictionary = {}
    # For each item in the list, use the 'count()' method to tally how
    # often it appears. Then, populate the dictionary with a key (the word)
    # and its corresponding value (the count).
    for word in words:
        dictionary[word] = words.count(word)
    return dictionary

print(word_count("I do not like it Sam I Am"))
Steven Parker
Steven Parker
218,692 Points

It looks like comments have been added into the code explaining each line already!

1 Answer

James Joseph
James Joseph
4,761 Points

Everything seems to be fine, the only thing I'd say is you probably shouldn't have the print section in the code there as most times they only want you to return the value not print out the function itself.

I'd also try avoiding using names like dictionary or dict to name your dictionary, maybe something like word_dict ?

Reason for that is to give it a meaningful name that is related to the function.