chapter five

5 Jump the Five: Working with dictionaries

 

"When I get up, nothing gets me down." - D. L. Roth

In an episode of the television show The Wire, drug dealers encode telephone numbers that they text in order to obscure them from the police who they assume are intercepting their messages. They use an algorithm we’ll call "Jump The Five" where a number is changed to the one that is opposite on a US telephone pad if you jump over the 5. You feel me?

jump pad

If we start with "1" and jump across the 5, we get to "9," then "6" jumps the 5 to become "4," and so forth. The numbers "5" and "0" will swap with each other. In this exercise, we’re going to write a Python program called jump.py that will take in some text as a positional argument. Each number in the text will be encoded using this algorithm. All non-number will pass through unchanged, for example:

$ ./jump.py 867-5309
243-0751
$ ./jump.py 'Call 1-800-329-8044 today!'
Call 9-255-781-2566 today!

We will need some way to inspect each character in the input text and identify the numbers. We will learn how to use a for loop for this and how that relates to a "list comprehension." Then we will need some way to associate a number like "1" with the number "9," and so on for all the numbers. We’ll learn about a data structure in Python called a "dictionary" type that allows us to do exactly that.

In this chapter, you will learn to:

5.1  Dictionaries

5.1.1  Creating a dictionary

5.1.2  Accessing dictionary values

5.1.3  Other dictionary methods

5.2  Writing jump.py

5.3  Solution

5.4  Discussion

5.4.1  Defining the arguments

5.4.2  Using a dict for encoding

5.4.3  Method 1: Using a for loop to print each character

5.4.4  Method 2: Using a for loop to build a new string

5.4.5  Method 3: Using a for loop to build a new list

5.4.6  Method 4: List comprehension

5.4.7  Method 5: str.translate