Online Book Reader

Home Category

Learning Python - Mark Lutz [135]

By Root 1738 0
operation) and can represent many types of structured information. For example, dictionaries are one of many ways to describe the properties of an item in your program’s domain; that is, they can serve the same role as “records” or “structs” in other languages.

The following, for example, fills out a dictionary by assigning to new keys over time:

>>> rec = {}

>>> rec['name'] = 'mel'

>>> rec['age'] = 45

>>> rec['job'] = 'trainer/writer'

>>>

>>> print(rec['name'])

mel

Especially when nested, Python’s built-in data types allow us to easily represent structured information. This example again uses a dictionary to capture object properties, but it codes it all at once (rather than assigning to each key separately) and nests a list and a dictionary to represent structured property values:

>>> mel = {'name': 'Mark',

... 'jobs': ['trainer', 'writer'],

... 'web': 'www.rmi.net/˜lutz',

... 'home': {'state': 'CO', 'zip':80513}}

To fetch components of nested objects, simply string together indexing operations:

>>> mel['name']

'Mark'

>>> mel['jobs']

['trainer', 'writer']

>>> mel['jobs'][1]

'writer'

>>> mel['home']['zip']

80513

Although we’ll learn in Part VI that classes (which group both data and logic) can be better in this record role, dictionaries are an easy-to-use tool for simpler requirements.

* * *

Why You Will Care: Dictionary Interfaces


Dictionaries aren’t just a convenient way to store information by key in your programs—some Python extensions also present interfaces that look like and work the same as dictionaries. For instance, Python’s interface to DBM access-by-key files looks much like a dictionary that must be opened. Strings are stored and fetched using key indexes:

import dbm

file = dbm.open("filename") # Link to file

file['key'] = 'data' # Store data by key

data = file['key'] # Fetch data by key

In Chapter 27, you’ll see that you can store entire Python objects this way, too, if you replace dbm in the preceding code with shelve (shelves are access-by-key databases of persistent Python objects). For Internet work, Python’s CGI script support also presents a dictionary-like interface. A call to cgi.FieldStorage yields a dictionary-like object with one entry per input field on the client’s web page:

import cgi

form = cgi.FieldStorage() # Parse form data

if 'name' in form:

showReply('Hello, ' + form['name'].value)

All of these, like dictionaries, are instances of mappings. Once you learn dictionary interfaces, you’ll find that they apply to a variety of built-in tools in Python.

* * *

Other Ways to Make Dictionaries

Finally, note that because dictionaries are so useful, more ways to build them have emerged over time. In Python 2.3 and later, for example, the last two calls to the dict constructor (really, type name) shown here have the same effect as the literal and key-assignment forms above them:

{'name': 'mel', 'age': 45} # Traditional literal expression

D = {} # Assign by keys dynamically

D['name'] = 'mel'

D['age'] = 45

dict(name='mel', age=45) # dict keyword argument form

dict([('name', 'mel'), ('age', 45)]) # dict key/value tuples form

All four of these forms create the same two-key dictionary, but they are useful in differing circumstances:

The first is handy if you can spell out the entire dictionary ahead of time.

The second is of use if you need to create the dictionary one field at a time on the fly.

The third involves less typing than the first, but it requires all keys to be strings.

The last is useful if you need to build up keys and values as sequences at runtime.

We met keyword arguments earlier when sorting; the third form illustrated in this code listing has become especially popular in Python code today, since it has less syntax (and hence there is less opportunity for mistakes). As suggested previously in Table 8-2, the last form in the listing is also commonly used in conjunction with the zip function, to combine separate lists of keys and values obtained dynamically at runtime (parsed out of a data file’s

Return Main Page Previous Page Next Page

®Online Book Reader