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

8. The dictionary type

Python dictionaries are one of its more powerful built-in types. They are generally used for look-up tables and many similar applications.

A Python dictionary represents a set of zero or more ordered pairs (ki, vi) such that:

Another term for this structure is mapping, since it maps the set of keys onto the set of values.

8.1. Operations on dictionaries

These operations are available on any dictionary object D:

len(D)Returns the number of entries in D.
D[k]

If D has an entry with key k, returns the corresponding value. If there is no such key, raises a KeyError exception.

D[k] = vSets the entry for key k to value v. If there was previously a value for that key, it is replaced.
del D[k]If there is an entry for key k, that entry is deleted. If not, a KeyError exception is raised.
D.has_key(k)Predicate that returns true if D has a key k.
D.items()A list of (key,value) tuples from D.
.keys()A list of all keys in D.
D.values()A list of all values in D, in the same order as D.keys().
D.update(E)Merge dictionary E into D. If the same key exists in both, use the value from E.
D.get(k,x)Same as D[k], but if no entry exists for key k, returns x, or None if x is omitted.
D.setdefault(k[,x])If D[k] exists, returns that value. If there is no element D[k], sets D[k] to x, defaulting to None, and returns that value.
D.iteritems()Returns an iterator over the (key, value) pairs of D.
D.iterkeys()Returns an iterator over the keys of D.
D.itervalues()Returns an iterator over the values of D.
D.popitem()Returns an arbitrary entry from D as a (key, value) tuple, and also removes that entry. If D is empty, raises a KeyError exception.
x in DTrue if x is a key in D.
x not in DTrue if x is not a key in D.