04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

116 CHAPTER 6 ■ ABSTRACTION<br />

storage = {}<br />

storage['first'] = {}<br />

storage['middle'] = {}<br />

storage['last'] = {}<br />

The data structure storage is a dictionary with three keys: 'first', 'middle', and 'last'.<br />

Under each of these keys, you store another dictionary. In these subdictionaries, you’ll use<br />

names (first, middle, or last) as keys, and insert lists of people as values. For example, to add me<br />

to this structure, you could do the following:<br />

>>> me = 'Magnus Lie Hetland'<br />

>>> storage['first']['Magnus'] = [me]<br />

>>> storage['middle']['Lie'] = [me]<br />

>>> storage['last']['Hetland'] = [me]<br />

Under each key, you store a list of people. In this case, the lists contain only me.<br />

Now, if you want a list of all the people registered who have the middle name Lie, you<br />

could do the following:<br />

>>> storage['middle']['Lie']<br />

['Magnus Lie Hetland']<br />

As you can see, adding people to this structure is a bit tedious, especially when you get<br />

more people with the same first, middle, or last names, because then you have to extend the list<br />

that is already stored under that name. Let’s add my sister, for example, and let’s assume you<br />

don’t know what is already stored in the database:<br />

>>> my_sister = 'Anne Lie Hetland'<br />

>>> storage['first'].setdefault('Anne', []).append(my_sister)<br />

>>> storage['middle'].setdefault('Lie', []).append(my_sister)<br />

>>> storage['last'].setdefault('Hetland', []).append(my_sister)<br />

>>> storage['first']['Anne']<br />

['Anne Lie Hetland']<br />

>>> storage['middle']['Lie']<br />

['Magnus Lie Hetland', 'Anne Lie Hetland']<br />

Imagine writing a large program filled with updates like this—it would quickly become<br />

quite unwieldy.<br />

The point of abstraction is to hide all the gory details of the updates, and you can do that<br />

with functions. Let’s first make a function to initialize a data structure:<br />

def init(data):<br />

data['first'] = {}<br />

data['middle'] = {}<br />

data['last'] = {}<br />

In the preceding code, I’ve simply moved the initialization statements inside a function.<br />

You can use it like this:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!