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

16. Type dict: Dictionaries

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 (in the algebraic sense).

To create a new dictionary, use this general form:

{ k0: v0, k1: v1, ... }

There can be any number of key-value pairs (including zero). Each key-value has the form “ki:vi”, and pairs are separated by commas. Here are some examples of dictionaries:

{'Bolton': 'Notlob', 'Ipswich': 'Esher'}
{(1,1):48, (8,20): 52}

For efficiency reasons, the order of the pairs in a dictionary is arbitrary: it is essentially an unordered set of ordered pairs. If you display a dictionary, the pairs may be shown in a different order than you used when you created it.

>>> signals = {0:'red', 1: 'yellow', 2:'green'}
>>> signals
{2: 'green', 0: 'red', 1: 'yellow'}