7 Gashlycrumb: Looking items up in a dictionary

 

In this chapter, we’re going to look up lines of text from an input file that start with the letters provided by the user. The text will come from an input file that will default to Edward Gorey’s “The Gashlycrumb Tinies,” an abecedarian book that describes various and ghastly ways in which children expire. For instance, figure 7.1 shows that “N is for Neville who died of ennui.”

Table 7.1 N is for Neville who died of ennui.

Our gashlycrumb.py program will take one or more letters as positional arguments and will look up the lines of text that start with that letter from an optional input file. We will look up the letters in a case-insensitive fashion.

The input file will have the value for each letter on a separate line:

$ head -2 gashlycrumb.txt
A is for Amy who fell down the stairs.
B is for Basil assaulted by bears.

When our unfortunate user runs this program, here is what they will see:

$ ./gashlycrumb.py e f
E is for Ernest who choked on a peach.
F is for Fanny sucked dry by a leech.

In this exercise, you will

7.1 Writing gashlycrumb.py

7.2 Solution

7.3 Discussion

7.3.1 Handling the arguments

7.3.2 Reading the input file

7.3.3 Using a dictionary comprehension

7.3.4 Dictionary lookups

7.4 Going further

Summary