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 trialMd Akibe Hashan
2,422 Pointsword_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"))
1 Answer
James Joseph
4,885 PointsEverything 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.
Steven Parker
231,236 PointsSteven Parker
231,236 PointsIt looks like comments have been added into the code explaining each line already!