.. _python_dict: ============================================================= Python dictionaries ============================================================= Dictionaries are a useful data type in Python for various purposes. Below are some examples. Dictionaries are created using the curly brackets `{...}`. They can be indexed into like lists or tuples, but instead of having the indexes 0, 1, 2, ... the `keys` can be any immutable Python objects. Here is a dictionary with 3 keys: 1, 50, 1000. The value for each key is the number written as a string:: >>> d = {1:'one', 50:'fifty', 1000:'one thousand'} >>> d[1] 'one' >>> d[50] 'fifty' >>> d[2] Traceback (most recent call last): File "", line 1, in KeyError: 2 The value for key 2 has not yet been defined, but we can define it now:: >>> d[2] = 'two' >>> d {1000: 'one thousand', 1: 'one', 50: 'fifty', 2: 'two'} The keys do not have to be integers, they can be any immutable object, e.g.:: >>> colors = {} # empty dictionary >>> colors['red'] = '#ff0000' >>> colors['blue'] = '#0000ff' if you want to keep track of the html string for various colors (see :ref:`colors`). .. _dict_attr: Dictionary methods --------------------- Several methods are defined on dictionaries, e.g. :: >>> colors.keys() ['blue', 'red'] >>> colors.values() ['#0000ff', '#ff0000'] >>> colors.items() [('blue', '#0000ff'), ('red', '#ff0000')] Note that each returns a list. The last returns a list of tuples. To iterate over a dictionary, you can iterate over one of the lists above, or to avoid having Python create a list (useful when the dictionary is very large), you can use the `iteritems` method, which returns an iterable in the form of tuples `(key,value)`:: >>> for key,value in colors.iteritems(): ... print "%s : %s" % (key.rjust(10), value) ... blue : #0000ff red : #ff0000 Note that `key.rjust(10)` right justifies the key in a field of 10 characters. If the key might not be a string, you could use `str(key).rjust(10)`, e.g. :: >>> for k,v in d.iteritems(): ... print "%s : %s" % (str(k).rjust(10), v) ... 1000 : one thousand 1 : one 50 : fifty 2 : two Note that ordering of items in the dictionary can be quite random. If the keys have some natural ordering and you want to process them in this order, try something like:: >>> keys = d.keys() >>> keys [1000, 1, 50, 2] >>> keys.sort() >>> keys [1, 2, 50, 1000] >>> for k in keys: ... print "%s : %s" % (str(k).rjust(10), d[k]) ... 1 : one 2 : two 50 : fifty 1000 : one thousand Further reading --------------- * ``_ * ``_