Count the words
Write word_counts(text) that returns a dictionary mapping each word to how many times it appears. Treat upper and lower case as the same word.
word_counts("To be or not to be")
# {"to": 2, "be": 2, "or": 1, "not": 1}
Show hint
d.get(key, 0) returns 0 when the key is not in the dictionary yet.
Show solution
def word_counts(text):
counts = {}
for word in text.lower().split():
counts[word] = counts.get(word, 0) + 1
return counts
Lower-casing first makes "To" and "to" the same key. get with a default avoids a special case for new words. collections.Counter(text.lower().split()) does the same in one line.
Want a problem like this every day? See today's problem and keep a streak going.