Bob Smith 10000
Sue Jones 20000
>>> [person[0][1] for person in people] # collect names
['Bob Smith', 'Sue Jones']
>>> for person in people:
print(person[0][1].split()[-1]) # get last names
person[2][1] *= 1.10 # give a 10% raise
Smith
Jones
>>> for person in people: print(person[2])
['pay', 11000.0]
['pay', 22000.0]
All we’ve really done here is add an extra level of positional indexing. To do better, we
might inspect field names in loops to find the one we want (the loop uses tuple assign-
ment here to unpack the name/value pairs):
>>> for person in people:
for (name, value) in person:
if name == 'name': print(value) # find a specific field
Bob Smith
Sue Jones
Better yet, we can code a fetcher function to do the job for us:
>>> def field(record, label):
for (fname, fvalue) in record:
if fname == label: # find any field by name
return fvalue
>>> field(bob, 'name')
'Bob Smith'
>>> field(sue, 'pay')
22000.0
>>> for rec in people:
print(field(rec, 'age')) # print all ages
42
45
If we proceed down this path, we’ll eventually wind up with a set of record interface
functions that generically map field names to field data. If you’ve done any Python
coding in the past, though, you probably already know that there is an easier way to
code this sort of association, and you can probably guess where we’re headed in the
next section.
8 | Chapter 1: A Sneak Preview
Do
wnload from Wow! eBook <www.wowebook.com>