Next: Functions and Methods for Up: Lists, Tuples and Dictionaries Previous: Functions and Methods for   Contents

# Dictionaries

Dictionaries (sometimes refered to as associative arrays or hashes) are very similar to lists in that they can contain arbitrary objects and can be nested to any desired depth, but, instead of being indexed by integers, they can be indexed by any immutable object, such as strings or tuples. Since humans can more easily associate information with strings than with arbitrary numbers, dictionaries are an especially convenient way to keep track of information within a program.

As a simple example of a dictionary, consider a phonebook. We could store phone numbers as tuples inside a list, with the first tuple element being the name of the person and the second tuple element being the phone number:

```>>> phonelist = [('Fred','555-1231'),('Andy','555-1195'),('Sue','555-2193')]
```
However, to find, say, Sue's phone number, we'd have to search each element of the list to find the tuple with Sue as the first element in order to find the number we wanted. With a dictionary, we can use the person's name as the index to the array. In this case, the index is usually refered to as a key. This makes it very easy to find the information we're looking for:
```>>> phonedict = {'Fred':'555-1231','Andy':'555-1195','Sue':'555-2193'}
>>> phonedict['Sue']
'555-2193'
```
As the above example illustrates, we can initialize a dictionary with a comma-separated list of key/value pairs, separated by colons, and surrounded by curly braces. An empty dictionary can be expressed by a set of empty curly braces (`{}`).

Dictionary keys are not limited to strings, nor do all the keys of a dictionary need be of the same type. However, mutable objects such as lists can not be used as dictionary keys and an attempt to do so will raise a TypeError. To index a dictionary with multiple values, a tuple can be used:

```>>> tupledict = {(7,3):21,(13,4):52,(18,5):90}
```
Since the tuples used as keys in the dictionary consist of numbers, any tuple containing expressions resulting in the same numbers can be used to index the dictionary:
```>>> tupledict[(4+3,2+1)]
21
```

In addition to initializing a dictionary as described above, you can add key/value pairs to a dictionary using assignment statements:

```>>> tupledict[(19,5)] = 95
>>> tupledict[(14,2)] = 28
```
To eliminate a key/value pair from a dictionary use the del statement.

Next: Functions and Methods for Up: Lists, Tuples and Dictionaries Previous: Functions and Methods for   Contents
Phil Spector 2003-11-12