O'Reilly logo

A Concise Introduction to Programming in Python by Mark J. Johnson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 s.split()
10
11 def frequency(words):
12 d = {}
13 for word in words:
14  ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required