Chapter 18
Dictionaries
Imagine writing a program that counts the number of times each word appears
in a large file. We could store the counts in a list, but then how do we keep
track of which word uses which index? We could store the words in a separate
second list, so that the count for the word in words[i] is in counts[i], but
then we would have to search the entire word list every time we came to
another word to count. A dictionary is much more efficient.
Listing 18.1: Word Frequency
1 # wordfreq.py
2
3 import string
4
5 def getwords(fname):
6 with open(fname) as f:
7 s = f.read().lower()
8 s = s.translate(s.maketrans("", "", string.punctuation))
9 return

Get A Concise Introduction to Programming in Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.