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
valuecan be any type.Each
keymay occur only once in the dictionary.No
keymay be mutable. In particular, a key may not be a list or dictionary, or a tuple containing a list or dictionary, and so on.
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:
{k1: v1, k2: v2, ...}
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
“din” operator, like this:
kind
This operation returns True if is a key in
dictionary k,
dFalse otherwise.
The construct “”
is the inverse test: it returns k not in dTrue if
is
not a key in k, dFalse 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