Python Python Collections (2016, retired 2019) Dictionaries Word Count

Md Akibe Hashan
Md Akibe Hashan
2,408 Points

word_count

anyone please explain me how every line of this working

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(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
203,700 Points

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

1 Answer

James Joseph
James Joseph
2,583 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.