O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 dicts

This 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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required