5.6 Dictionaries

A dictionary (also sometimes called an associative array) is a mapping from 'hashable' objects (e.g., strings, numbers, and tuples of such; see the Python documentation http://docs.python.org/tut/node7.htmland http://docs.python.org/lib/typesmapping.html for details) to arbitrary objects.

sage: d = {1:5, 'sage':17, ZZ:GF(7)}
sage: type(d)
<type 'dict'>
sage: d.keys()
 [1, 'sage', Integer Ring]
sage: d['sage']
17
sage: d[ZZ]
Finite Field of size 7
sage: d[1]
5

The third key illustrates that the indexes of a dictionary can be complicated, e.g., the ring of integers.

You can turn the above dictionary into a list with the same data:

sage: d.items()
[(1, 5), ('sage', 17), (Integer Ring, Finite Field of size 7)]
A common idiom is to iterate through the pairs in a dictionary:
sage: d = {2:4, 3:9, 4:16}
sage: [a*b for a, b in d.iteritems()]
[8, 27, 64]

A dictionary is unordered, as the last output illustrates.

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