Think Python/Dictionaries

A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type.

You can think of a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps to a value. The association of a key and a value is called a key-value pair or sometimes an item.

As an example, we'll build a dictionary that maps from English to Spanish words, so the keys and the values are all strings.

The function dict creates a new dictionary with no items. Because dict is the name of a built-in function, you should avoid using it as a variable name.

The squiggly-brackets,, represent an empty dictionary. To add items to the dictionary, you can use square brackets:

This line creates an item that maps from the key &#X2019;one&#X2019; to the value. If we print the dictionary again, we see a key-value pair with a colon between the key and value: This output format is also an input format. For example, you can create a new dictionary with three items: But if you print eng2sp, you might be surprised: The order of the key-value pairs is not the same. In fact, if you type the same example on your computer, you might get a different result. In general, the order of items in a dictionary is unpredictable.

But that&#X2019;s not a problem because the elements of a dictionary are never indexed with integer indices. Instead, you use the keys to look up the corresponding values: The key &#X2019;two&#X2019; always maps to the value  so the order of the items doesn&#X2019;t matter.

If the key isn&#X2019;t in the dictionary, you get an exception:

The len function works on dictionaries; it returns the number of key-value pairs:

The in operator works on dictionaries; it tells you whether something appears as a key in the dictionary (appearing as a value is not good enough).

To see whether something appears as a value in a dictionary, you can use the method values, which returns the values as a list, and then use the <TT>in</TT> operator:

You can do the same with <TT>keys</TT>:

The <TT>in</TT> operator uses different algorithms for lists and dictionaries. For lists, it uses a search algorithm, as in Section&#XA0;8.6. As the list gets longer, the search time gets longer in direct proportion. For dictionaries, Python uses an algorithm called a hashtable that has a remarkable property: the <TT>in</TT> operator takes about the same amount of time no matter how many items there are in a dictionary. I won&#X2019;t explain how that&#X2019;s possible, but you can read more about it at <TT>wikipedia.org/wiki/Hash_table</TT>.

Exercise 1
Write a function that reads the words in <TT>words.txt</TT> ''and stores them as keys in a dictionary. It doesn&#X2019;t matter what the values are. Then you can use the <TT>in</TT> operator as a fast way to check whether a string is in the dictionary.''

If you did Exercise&#XA0;'10.8', you can compare the speed of this implementation with the list '<TT>in</TT>' operator and the bisection search.

Dictionary as a set of counters
Suppose you are given a string and you want to count how many times each letter appears. There are several ways you could do it:


 * You could create 26 variables, one for each letter of the alphabet. Then you could traverse the string and, for each character, increment the corresponding counter, probably using a chained conditional.
 * You could create a list with 26 elements. Then you could convert each character to a number (using the built-in function <TT>ord</TT>), use the number as an index into the list, and increment the appropriate counter.
 * You could create a dictionary with characters as keys and counters as the corresponding values. The first time you see a character, you would add an item to the dictionary. After that you would increment the value of an existing item.

Each of these options performs the same computation, but each of them implements that computation in a different way.

An implementation is a way of performing a computation; some implementations are better than others. For example, an advantage of the dictionary implementation is that we don&#X2019;t have to know ahead of time which letters appear in the string and we only have to make room for the letters that do appear.

Here is what the code might look like: The name of the function is histogram, which is a statistical term for a set of counters (or frequencies).

The first line of the function creates an empty dictionary. The <TT>for</TT> loop traverses the string. Each time through the loop, if the character <TT>c</TT> is not in the dictionary, we create a new item with key <TT>c</TT> and the initial value 1 (since we have seen this letter once). If <TT>c</TT> is already in the dictionary we increment <TT>d[c]</TT>.

Here&#X2019;s how it works: The histogram indicates that the letters <TT>&#X2019;a&#X2019;</TT> and appear once;  appears twice, and so on.

Exercise 2
''Dictionaries have a method called '<TT>get</TT>' that takes a key and a default value. If the key appears in the dictionary, '<TT>get</TT>' returns the corresponding value; otherwise it returns the default value. For example:'' ''Use '<TT>get</TT>' to write '<TT>histogram</TT>' more concisely. You should be able to eliminate the '<TT>if</TT>' statement.''

Looping and dictionaries
If you use a dictionary in a <TT>for</TT> statement, it traverses the keys of the dictionary. For example, prints each key and the corresponding value: Here&#X2019;s what the output looks like: Again, the keys are in no particular order.

Exercise 3
Dictionaries have a method called '<TT>keys</TT>' that returns the keys of the dictionary, in no particular order, as a list.

Modify  to print the keys and their values in alphabetical order.

Reverse lookup
Given a dictionary <TT>d</TT> and a key <TT>k</TT>, it is easy to find the corresponding value <TT>v = d[k]</TT>. This operation is called a lookup.

But what if you have <TT>v</TT> and you want to find <TT>k</TT>? You have two problems: first, there might be more than one key that maps to the value <TT>v</TT>. Depending on the application, you might be able to pick one, or you might have to make a list that contains all of them. Second, there is no simple syntax to do a reverse lookup; you have to search.

Here is a function that takes a value and returns the first key that maps to that value: This function is yet another example of the search pattern, but it uses a feature we haven&#X2019;t seen before, <TT>raise</TT>. The <TT>raise</TT> statement causes an exception; in this case it causes a <TT>ValueError</TT>, which generally indicates that there is something wrong with the value of a parameter.

If we get to the end of the loop, that means <TT>v</TT> doesn&#X2019;t appear in the dictionary as a value, so we raise an exception.

Here is an example of a successful reverse lookup: And an unsuccessful one: The result when you raise an exception is the same as when Python raises one: it prints a traceback and an error message.

The <TT>raise</TT> statement takes a detailed error message as an optional argument. For example: A reverse lookup is much slower than a forward lookup; if you have to do it often, or if the dictionary gets big, the performance of your program will suffer. <DIV CLASS="theorem">Exercise&#XA0;4&#XA0;&#XA0;Modify  so that it builds and returns a list of all keys that map to <TT>v</TT> , or an empty list if there are none.</DIV>

Dictionaries and lists
Lists can appear as values in a dictionary. For example, if you were given a dictionary that maps from letters to frequencies, you might want to invert it; that is, create a dictionary that maps from frequencies to letters. Since there might be several letters with the same frequency, each value in the inverted dictionary should be a list of letters.

Here is a function that inverts a dictionary: Each time through the loop, <TT>key</TT> gets a key from <TT>d</TT> and <TT>val</TT> gets the corresponding value. If <TT>val</TT> is not in <TT>inv</TT>, that means we haven&#X2019;t seen it before, so we create a new item and initialize it with a singleton (a list that contains a single element). Otherwise we have seen this value before, so we append the corresponding key to the list.

Here is an example: And here is a diagram showing <TT>hist</TT> and <TT>inv</TT>:

<DIV CLASS="center"><IMG SRC="book018.png"></DIV> A dictionary is represented as a box with the type <TT>dict</TT> above it and the key-value pairs inside. If the values are integers, floats or strings, I usually draw them inside the box, but I usually draw lists outside the box, just to keep the diagram simple.

Lists can be values in a dictionary, as this example shows, but they cannot be keys. Here&#X2019;s what happens if you try:

I mentioned earlier that a dictionary is implemented using a hashtable and that means that the keys have to be hashable.

A hash is a function that takes a value (of any kind) and returns an integer. Dictionaries use these integers, called hash values, to store and look up key-value pairs.

This system works fine if the keys are immutable. But if the keys are mutable, like lists, bad things happen. For example, when you create a key-value pair, Python hashes the key and stores it in the corresponding location. If you modify the key and then hash it again, it would go to a different location. In that case you might have two entries for the same key, or you might not be able to find a key. Either way, the dictionary wouldn&#X2019;t work correctly.

That&#X2019;s why the keys have to be hashable, and why mutable types like lists aren&#X2019;t. The simplest way to get around this limitation is to use tuples, which we will see in the next chapter.

Since dictionaries are mutable, they can&#X2019;t be used as keys, but they can be used as values.

Exercise 5
Read the documentation of the dictionary method <TT>setdefault</TT> and use it to write a more concise version of  .

Memos
If you played with the <TT>fibonacci</TT> function from Section&#XA0;6.7, you might have noticed that the bigger the argument you provide, the longer the function takes to run. Furthermore, the run time increases very quickly.

To understand why, consider this call graph for <TT>fibonacci</TT> with <TT>n=4</TT>: <DIV CLASS="center"><IMG SRC="book019.png"></DIV> A call graph shows a set of function frames, with lines connecting each frame to the frames of the functions it calls. At the top of the graph, <TT>fibonacci</TT> with <TT>n=4</TT> calls <TT>fibonacci</TT> with <TT>n=3</TT> and <TT>n=2</TT>. In turn, <TT>fibonacci</TT> with <TT>n=3</TT> calls <TT>fibonacci</TT> with <TT>n=2</TT> and <TT>n=1</TT>. And so on.

Count how many times <TT>fibonacci(0)</TT> and <TT>fibonacci(1)</TT> are called. This is an inefficient solution to the problem, and it gets worse as the argument gets bigger.

One solution is to keep track of values that have already been computed by storing them in a dictionary. A previously computed value that is stored for later use is called a memo. Here is an implementation of <TT>fibonacci</TT> using memos: <TT>known</TT> is a dictionary that keeps track of the Fibonacci numbers we already know. It starts with two items: 0 maps to 0 and 1 maps to 1.

Whenever <TT>fibonacci</TT> is called, it checks <TT>known</TT>. If the result is already there, it can return immediately. Otherwise it has to compute the new value, add it to the dictionary, and return it.

Exercise 6
Run this version of '<TT>fibonacci</TT>' and the original with a range of parameters and compare their run times.

Global variables
In the previous example, <TT>known</TT> is created outside the function, so it belongs to the special frame called. Variables in  are sometimes called global because they can be accessed from any function. Unlike local variables, which disappear when their function ends, global variables persist from one function call to the next.

It is common to use global variables for flags; that is, boolean variables that indicate (&#X201C;flag&#X201D;) whether a condition is true. For example, some programs use a flag named <TT>verbose</TT> to control the level of detail in the output: If you try to reassign a global variable, you might be surprised. The following example is supposed to keep track of whether the function has been called:

But if you run it you will see that the value of doesn&#X2019;t change. The problem is that <TT>example2</TT> creates a new local variable named. The local variable goes away when the function ends, and has no effect on the global variable.

To reassign a global variable inside a function you have to declare the global variable before you use it: The <TT>global</TT> statement tells the interpreter something like, &#X201C;In this function, when I say, I mean the global variable; don&#X2019;t create a local one.&#X201D;

Here&#X2019;s an example that tries to update a global variable: If you run it you get:

Python assumes that <TT>count</TT> is local, which means that you are reading it before writing it. The solution, again, is to declare <TT>count</TT> global.

If the global value is mutable, you can modify it without declaring it:

So you can add, remove and replace elements of a global list or dictionary, but if you want to reassign the variable, you have to declare it:

Long integers
If you compute <TT>fibonacci(50)</TT>, you get: The <TT>L</TT> at the end indicates that the result is a long integer, or type <TT>long</TT>.

Values with type <TT>int</TT> have a limited range; long integers can be arbitrarily big, but as they get bigger they consume more space and time.

The mathematical operators work on long integers, and the functions in the <TT>math</TT> module, too, so in general any code that works with <TT>int</TT> will also work with <TT>long</TT>.

Any time the result of a computation is too big to be represented with an integer, Python converts the result as a long integer: In the first case the result has type <TT>int</TT>; in the second case it is <TT>long</TT>.

Exercise 7
''Exponentiation of large integers is the basis of common algorithms for public-key encryption. Read the Wikipedia page on the RSA algorithm and write functions to encode and decode messages.''

Debugging
As you work with bigger datasets it can become unwieldy to debug by printing and checking data by hand. Here are some suggestions for debugging large datasets: <DL CLASS="description"><DT CLASS="dt-description">Scale down the input:</DT><DD CLASS="dd-description"> If possible, reduce the size of the dataset. For example if the program reads a text file, start with just the first 10 lines, or with the smallest example you can find. You can either edit the files themselves, or (better) modify the program so it reads only the first <TT>n</TT> lines. If there is an error, you can reduce <TT>n</TT> to the smallest value that manifests the error, and then increase it gradually as you find and correct errors. </DD><DT CLASS="dt-description">Check summaries and types:</DT><DD CLASS="dd-description"> Instead of printing and checking the entire dataset, consider printing summaries of the data: for example, the number of items in a dictionary or the total of a list of numbers. A common cause of runtime errors is a value that is not the right type. For debugging this kind of error, it is often enough to print the type of a value. </DD><DT CLASS="dt-description">Write self-checks:</DT><DD CLASS="dd-description"> Sometimes you can write code to check for errors automatically. For example, if you are computing the average of a list of numbers, you could check that the result is not greater than the largest element in the list or less than the smallest. This is called a &#X201C;sanity check&#X201D; because it detects results that are &#X201C;insane.&#X201D;

Another kind of check compares the results of two different computations to see if they are consistent. This is called a &#X201C;consistency check.&#X201D; </DD><DT CLASS="dt-description">Pretty print the output:</DT><DD CLASS="dd-description"> Formatting debugging output can make it easier to spot an error. We saw an example in Section&#XA0;6.9. The <TT>pprint</TT> module provides a <TT>pprint</TT> function that displays built-in types in a more human-readable format.

</DD></DL> Again, time you spend building scaffolding can reduce the time you spend debugging.

Glossary
<DL CLASS="description"><DT CLASS="dt-description">dictionary:</DT><DD CLASS="dd-description"> A mapping from a set of keys to their corresponding values. </DD><DT CLASS="dt-description">key-value pair:</DT><DD CLASS="dd-description"> The representation of the mapping from a key to a value. </DD><DT CLASS="dt-description">item:</DT><DD CLASS="dd-description"> Another name for a key-value pair. </DD><DT CLASS="dt-description">key:</DT><DD CLASS="dd-description"> An object that appears in a dictionary as the first part of a key-value pair. </DD><DT CLASS="dt-description">value:</DT><DD CLASS="dd-description"> An object that appears in a dictionary as the second part of a key-value pair. This is more specific than our previous use of the word &#X201C;value.&#X201D; </DD><DT CLASS="dt-description">implementation:</DT><DD CLASS="dd-description"> A way of performing a computation. </DD><DT CLASS="dt-description">hashtable:</DT><DD CLASS="dd-description"> The algorithm used to implement Python dictionaries. </DD><DT CLASS="dt-description">hash function:</DT><DD CLASS="dd-description"> A function used by a hashtable to compute the location for a key. </DD><DT CLASS="dt-description">hashable:</DT><DD CLASS="dd-description"> A type that has a hash function. Immutable types like integers, floats and strings are hashable; mutable types like lists and dictionaries are not. </DD><DT CLASS="dt-description">lookup:</DT><DD CLASS="dd-description"> A dictionary operation that takes a key and finds the corresponding value. </DD><DT CLASS="dt-description">reverse lookup:</DT><DD CLASS="dd-description"> A dictionary operation that takes a value and finds one or more keys that map to it. </DD><DT CLASS="dt-description">singleton:</DT><DD CLASS="dd-description"> A list (or other sequence) with a single element. </DD><DT CLASS="dt-description">call graph:</DT><DD CLASS="dd-description"> A diagram that shows every frame created during the execution of a program, with an arrow from each caller to each callee.

</DD><DT CLASS="dt-description">histogram:</DT><DD CLASS="dd-description"> A set of counters. </DD><DT CLASS="dt-description">memo:</DT><DD CLASS="dd-description"> A computed value stored to avoid unnecessary future computation. </DD><DT CLASS="dt-description">global variable:</DT><DD CLASS="dd-description"> A variable defined outside a function. Global variables can be accessed from any function. </DD><DT CLASS="dt-description">flag:</DT><DD CLASS="dd-description"> A boolean variable used to indicate whether a condition is true. </DD><DT CLASS="dt-description">declaration:</DT><DD CLASS="dd-description"> A statement like <TT>global</TT> that tells the interpreter something about a variable. </DD></DL>

Exercise-8
Dictionaries have a method called 'keys' that returns the keys of the dictionary, in no particular order, as a list. Modify print_hist to print the keys and their values in alphabetical order.

Exercise 9
Two words are &#X201C;rotate pairs&#X201D; if you can rotate one of them and get the other (see  in Exercise&#XA0;'8.12').

Write a program that reads a wordlist and finds all the rotate pairs.

Exercise 10
Here&#X2019;s another Puzzler from Car Talk :

<BLOCKQUOTE CLASS="quote">''This was sent in by a fellow named Dan O&#X2019;Leary. He came upon a common one-syllable, five-letter word recently that has the following unique property. When you remove the first letter, the remaining letters form a homophone of the original word, that is a word that sounds exactly the same. Replace the first letter, that is, put it back and remove the second letter and the result is yet another homophone of the original word. And the question is, what&#X2019;s the word?''

''Now I&#X2019;m going to give you an example that doesn&#X2019;t work. Let&#X2019;s look at the five-letter word, &#X2018;wrack.&#X2019; W-R-A-C-K, you know like to &#X2018;wrack with pain.&#X2019; If I remove the first letter, I am left with a four-letter word, &#X2019;R-A-C-K.&#X2019; As in, &#X2018;Holy cow, did you see the rack on that buck! It must have been a nine-pointer!&#X2019; It&#X2019;s a perfect homophone. If you put the &#X2018;w&#X2019; back, and remove the &#X2018;r,&#X2019; instead, you&#X2019;re left with the word, &#X2018;wack,&#X2019; which is a real word, it&#X2019;s just not a homophone of the other two words.''

''But there is, however, at least one word that Dan and we know of, which will yield two homophones if you remove either of the first twoletters to make two, new four-letter words. The question is, what&#X2019;s the word?'' </BLOCKQUOTE>

You can use the dictionary from Exercise&#XA0;'11.1' to check whether a string is in the word list.

''To check whether two words are homophones, you can use the CMU Pronouncing Dictionary. You can download it from <TT>www.speech.cs.cmu.edu/cgi-bin/cmudict</TT> or from <TT>thinkpython.com/code/c06d</TT> and you can also download <TT>thinkpython.com/code/pronounce.py</TT> , which provides a function named  that reads the pronouncing dictionary and returns a Python dictionary that maps from each word to a string that describes its primary pronunciation.''

''Write a program that lists all the words that solve the Puzzler. You can see my solution at <TT>thinkpython.com/code/homophone.py</TT> .''