You are a guest. Restricted access. Read more

Dictionaries

Dictionaries are similar to what their name suggests - a dictionary. In a dictionary, we have an 'index' of words, and for each of them a definition. In Python, the word is called a 'key', and the definition a 'value'. The values in a dictionary are not numbered, unlike the lists.

Let us make a small dictionary:


data = dict()
data['hello'] = 'hola'
data['yes'] = 'si'
data['one'] = 'uno'
data['two'] = 'dos'
print data

What do you see?

To retrieve a value corresponding to a given key, just use the key:


data = dict()
data['hello'] = 'hola'
data['yes'] = 'si'
data['one'] = 'uno'
print data['hello']

What do you see?

A dictionary is defined using a shortcut {} instead of calling dict():


data = {}
data['hello'] = 'hola'
print data

One can also create a dictionary during its initialisation:


data = {'hello':'hola'}
print data

Let us now make a loop over keys of a dictionary:


data = {}
data['hello'] = 'hola'
data['yes'] = 'si'
data['one'] = 'uno'
data['two'] = 'dos'
for key, value in data.iteritems():
    print "%s -> %s" % (key, value)

python/collections/dictionaries.txt · Last modified: 2013/04/14 16:52 (external edit)
Back to top
CC Attribution-Share Alike 3.0 Unported
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0