[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
>>> curs.execute('select * from people')
>>> colnames = [desc[0] for desc in curs.description]
>>> colnames
['name', 'job', 'pay']

>>> for row in curs.fetchall():
... for name, value in zip(colnames, row):
... print(name, '\t=>', value)
... print()
...
name => Sue
job => mus
pay => 70000

name => Ann
job => mus
pay => 65000

name => Kim
job => adm
pay => 65000

Notice how a tab character is used to try to make this output align; a better approach
might be to determine the maximum field name length (we’ll see how in a later
example).


Record dictionaries construction


It’s a minor extension of our formatted display code to create a dictionary for each
record, with field names for keys—we just need to fill in the dictionary as we go:


>>> curs.execute('select * from people')
>>> colnames = [desc[0] for desc in curs.description]
>>> rowdicts = []
>>> for row in curs.fetchall():
... newdict = {}
... for name, val in zip(colnames, row):
... newdict[name] = val
... rowdicts.append(newdict)
...
>>> for row in rowdicts: print(row)
...
{'pay': 70000, 'job': 'mus', 'name': 'Sue'}
{'pay': 65000, 'job': 'mus', 'name': 'Ann'}
{'pay': 65000, 'job': 'adm', 'name': 'Kim'}

Because this is Python, though, there are more powerful ways to build up these record
dictionaries. For instance, the dictionary constructor call accepts the zipped name/
value pairs to fill out the dictionaries for us:


>>> curs.execute('select * from people')
>>> colnames = [desc[0] for desc in curs.description]
>>> rowdicts = []
>>> for row in curs.fetchall():
... rowdicts.append( dict(zip(colnames, row)) )

1340 | Chapter 17: Databases and Persistence

Free download pdf