Data as Dictionaries
Another useful and powerful
representation of data is as a dictionary of keys and values. This
leads to a much easier syntax when you edit and modify records; the
field names can be used rather than numeric indexes. It’s also
useful when putting together data about the same thing from different
sources. There will be some overlap between fields, but not total
agreement. Dictionaries can represent sparse data compactly. A classic example is
found in the Transaction architecture from Part 2, where there was a method to convert a
transaction to a list of dictionaries. A sales transaction has
different keys and values from a payroll transaction.
You’ll rarely want just one dictionary, so we have added the
following method to convert a
DataSet
to a list of dictionaries:
class DataSet:
<continued...>
def asDicts(self):
"returns a list of dictionaries, each with all fieldnames"
dicts = []
fieldcount = len(self.fieldnames)
for row in self.data:
dict = {}
for i in range(fieldcount):
dict[self.fieldnames[i]] = row[i]
dicts.append(dict)
return dictsThis enables you to get a row from a query and modify it flexibly:
let’s grab our first invoice from the sample database and look
at it. Assume you’ve just done a 'Select
*
FROM
Invoices' in a cursor:
>>> dict = ds.asDicts()[0] # grab the first one >>> pprint(dict) {'ClientID': 'MEGAWAD', 'Comments': None, 'Consultant': 'Joe Hacker', 'DatePaid': None, 'ExpenseDetails': None, 'Expenses': 0.0, 'HourlyRate': 50.0, 'Hours': 42.0, ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access