2.1.6 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 k (1)
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 (key, value) pairs (2)
a.keys() a copy of a's list of keys (2)
a.update(b) for k in b.keys(): a[k] = b[k] (3)
a.values() a copy of a's list of values (2)
a.get(k[, x]) a[k] if a.has_key(k), else x (4)
a.setdefault(k[, x]) a[k] if a.has_key(k), else x (also setting it) (5)
a.popitem() remove and return an arbitrary (key, value) pair (6)


Raises a KeyError exception if k is not in the map.

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())".

b must be of the same type as a.

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.

setdefault() is like get(), except that if k is missing, x is both returned and inserted into the dictionary as the value of k.

popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms.

See About this document... for information on suggesting changes.