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`

) such that:`value`

The

can be any type.`value`

Each

may occur only once in the dictionary.`key`

No

may be a list or dictionary.`key`

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.

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

{:`k`

_{1},`v`

_{1}:`k`

_{2}`v`

_{2}, ...}

To retrieve the value associated with key

from dictionary
`k`

, use an
expression of this form:
`d`

[`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

in dictionary `k`

, use an assignment statement of
this form:
`d`

[`d`

] =`k`

`v`

For example:

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

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

exists in a dictionary `k`

with the
“`d`

`in`

” operator, like this:

in`k`

`d`

This operation returns `True`

if

is a key in
dictionary `k`

,
`d`

`False`

otherwise.

The construct “

”
is the inverse test: it returns * k* not in

`d`

`True`

if
`k`

is
`d`

, `False`

if it
>>> 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