Dictionaries
Description
Python dictionaries can hold a variety of things from variables to objects. The power of dictionaries is not obvious when you first examine the dictionary. When you store an object in a dictionary you can pass the dictionary to a function and along with it you can pass all your objects. This makes it easier to create modular code.
Dictionaries consist of key : value pairs.
Running Python in a Terminal
To run Python in a terminal just open a terminal from Applications > Accessories > Terminal and type in python. Don’t type in the >>> that is the Python prompt.
Creating Dictionaries
Dictionaries can be created in many ways. Here are some examples using Python in a terminal. In the following example all five methods create the exact same dictionary.
a = dict(one=1, two=2, three=3) b = {'one': 1, 'two': 2, 'three': 3} c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) d = dict([('two', 2), ('one', 1), ('three', 3)]) e = dict({'three': 3, 'one': 1, 'two': 2}) f = {} f['one'] = 1 f['two'] = 2 f['three'] = 3 a == b == c == d == e == f True
Dictionaries can be updated in a couple of ways. The first way shown will update or add to the dictionary. If the key exists then the value is updated. If the key does not exist then the key : value pair is added to the dictionary.
a = dict(one=1, two=2, three=0) print a {'three': 0, 'two': 2, 'one': 1} a['three'] = 3 # update an existing entry a['four'] = 4 # add a new entry print a {'four': 4, 'three': 3, 'two': 2, 'one': 1}
You can add/update a dictionary with a dictionary using the update() function.
a = dict(one=1, two=2, three=0) b = {'four': 4, 'five': 5, 'six': 6} c = {} # create an empty dict c.update(a) c.update(b) print c {'four': 4, 'five': 5, 'two': 2, 'six': 6, 'three': 3, 'one': 1}
Passing a Dictionary
In this next example we will have a library file that will pass a dictionary of objects to the main program. The main program can act on the objects just as if they were created in the main program. This is the beginning of reusable libraries.