Mapping Types
-------------
A "mapping" object maps values of one type (the key type) to arbitrary
objects. Mappings are mutable objects. There is currently only one
standard mapping type, the "dictionary". A dictionary's keys are
almost arbitrary values. The only types of values not acceptable as
keys are values containing lists or dictionaries or other mutable types
that are compared by value rather than by object identity. Numeric
types used for keys obey the normal rules for numeric comparison: if
two numbers compare equal (e.g. `1' and `1.0') then they can be used
interchangeably to index the same dictionary entry.
Dictionaries are created by placing a comma-separated list of `KEY:
VALUE' pairs within braces, for example: `{'jack': 4098, 'sjoerd':
4127}' or `{4098: 'jack', 4127: 'sjoerd'}'.
The following operations are defined on mappings (where A and B are
mappings, K is a key, and V and X are arbitrary objects):
Operation Result Notes
------ ----- -----
len(A) the number of items in
A
A[K] the item of A with key (1)
K
A[K] = V set `A[K]' to V
del A[K] remove `A[K]' from A (1)
A.clear() remove all items from
`a'
A.copy() a (shallow) copy of `a'
A.has_key(K) `1' if A has a key K,
else `0'
A.items() a copy of A's list of (2)
(KEY, VALUE) pairs
A.keys() a copy of A's list of (2)
keys
A.update(B) `for k in B.keys(): (3)
A[k] = B[k]'
A.values() a copy of A's list of (2)
values
A.get(K[, X]) `A[K]' if (4)
`A.has_key(K)', else X
A.setdefault(K[, X]) `A[K]' if (5)
`A.has_key(K)', else X
(also setting it)
A.popitem() remove and return an (6)
arbitrary (KEY, VALUE)
pair
Notes:
`(1)'
Raises a `KeyError' exception if K is not in the map.
`(2)'
Keys and values are listed in random order. If `keys()' and
`values()' are called with no intervening modifications to the
dictionary, the two lists will directly correspond. This allows
the creation of `(VALUE, KEY)' pairs using `map()': `pairs =
map(None, A.values(), A.keys())'.
`(3)'
B must be of the same type as A.
`(4)'
Never raises an exception if K is not in the map, instead it
returns X. X is optional; when X is not provided and K is not in
the map, `None' is returned.
`(5)'
`setdefault()' is like `get()', except that if K is missing, X is
both returned and inserted into the dictionary as the value of K.
`(6)'
`popitem()' is useful to destructively iterate over a dictionary,
as often used in set algorithms.