A frequency dictionary maps each distinct item to the number of times it occurs. It is useful for counting letters in a Scrabble hand or words in a text. section 27.5
Counting words
Start with an empty dictionary, split the text into words, and visit each word. Add an unseen word with a count of 1; otherwise increase its existing count. Converting words to lowercase makes differently capitalized versions count together. section 27.5
Listing 27.4. Building a frequency dictionary
lyrics = "Happy birthday to you Happy birthday to you Happy birthday dear
Happy birthday to you" #1
counts = {} #2
words = lyrics.split(" ") #3
for w in words: #4
w = w.lower() #5
if w not in counts:
counts[w] = 1 #6
else:
counts[w] += 1 #7
print(counts) #8
Follow a small lyrics example from the input string to the printed dictionary of word counts. section 27.5
Listing 29.3. Making a frequency dictionary for words
def frequencies(words):
"""
words: list of words
returns: frequency dictionary for input words
"""
freq_dict = {} #1
for word in words: #2
if word in freq_dict: #3
freq_dict[word] += 1 #4
else: #5
freq_dict[word] = 1 #6
return freq_dict #7
freq_dict = frequencies(words) #8
See the counting logic packaged as a reusable frequencies function that accepts a list of words and returns a frequency dictionary. section 29.4
Frequency dictionaries also support larger tasks: comparing two documents by examining how their word counts differ. section 29.4 section 29.8
