Skip to content
scipython.com

Q4.2.5Grouping words by their length using a defaultdict

Modify Example E4.8 to use a defaultdict to produce a list of words, keyed by their length from the text of the first line of the Gettysburg Address.

Show solution

Here is a possible solution:

from collections import defaultdict

text = "Four score and seven years ago our fathers brought forth on this"\
    "continent, a new nation, conceived in Liberty, and dedicated to the"\
    "proposition that all men are created equal"
text = text.replace(',', '').lower()        # remove punctuation

word_lengths = defaultdict(int)
for word in text.split():
    word_lengths[word] += 1

for word, count in word_lengths.items():
    print('{}: {}'.format(word, count))

Output:

four: 1
score: 1
and: 2
seven: 1
years: 1
...