Next / Previous / Contents / TCC Help System / NM Tech homepage

5. Dictionaries

Python's dictionary type is useful for many applications involving table lookups. In mathematical terms:

A Python dictionary is a set of zero or more ordered pairs (key, value) such that:

  • The value can be any type.

  • Each key may occur only once in the dictionary.

  • No key may be a list or dictionary.

The idea is that you store values in a dictionary associated with some key, so that later you can use that key to retrieve the associated value.

5.1. Operations on dictionaries

The general form used to create a new dictionary in Python looks like this:

{k1: v1,  k2: v2,  ...}

To retrieve the value associated with key k from dictionary d, use an expression of this form:

d[k]

Here are some conversational examples:

>>> numberNames = {0:'zero', 1:'one', 10:'ten', 5:'five'}
>>> numberNames[10]
'ten'
>>> numberNames[0]
'zero'
>>> numberNames[999]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 999

Note that when you try to retrieve the value for which no key exists in the dictionary, Python raises a KeyError exception.

To add or replace the value for a key k in dictionary d, use an assignment statement of this form:

d[k] = v

For example:

>>> numberNames[2] = "two"
>>> numberNames[2]
'two'
>>> numberNames
{0: 'zero', 1: 'one', 10: 'ten', 2: 'two', 5: 'five'}

Note

The ordering of the pairs within a dictionary is undefined. Note that in the example above, the pairs do not appear in the order they were added.

You can use strings, as well as many other values, as keys:

>>> nameNo={"one":1, "two":2, "forty-leven":4011}
>>> nameNo["forty-leven"]
4011

You can test to see whether a key k exists in a dictionary d with the “in” operator, like this:

k in d

This operation returns True if k is a key in dictionary d, False otherwise.

The construct “k not in d” is the inverse test: it returns True if k is not a key in d, False if it is a key.

>>> 1 in numberNames
True
>>> 99 in numberNames
False
>>> "forty-leven" in nameNo
True
>>> "eleventeen" in nameNo
False
>>> "forty-leven" not in nameNo
False
>>> "eleventeen" not in nameNo
True

Python's del (delete) statement can be used to remove a key-value pair from a dictionary.

>>> numberNames
{0: 'zero', 1: 'one', 10: 'ten', 2: 'two', 5: 'five'}
>>> del numberNames[10]
>>> numberNames
{0: 'zero', 1: 'one', 2: 'two', 5: 'five'}
>>> numberNames[10]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 10