Better access to database search results

Gabriel Cooper gabriel.cooper at mediapulse.com
Tue Apr 12 11:32:58 EDT 2005


Usually when I access db search results it's something like this:

cursor.execute("select A1,A2,A3,A4 from B where C")
for (a1,a2,a3,a4) in cursor.fetchall():
    stuff()

But sometimes the point at which I use the data returned is not with the 
search, and so having the ability to access the results as a dictionary 
is more useful. I know that with MySQLdb I can open the connection and 
have it return a dictionary, but when only one search out of all the 
requests needs to be that way, it seems too much hassle to get a new 
cursor just for that. Also, as a web developer that uses python, my 
designers cognate "name.attribute" much easier than "name['attribute']" 
and so I came up with this function to help us both out.

Let me know what you think. Could this be done simpler?

def convert_cursor(cursor):
    '''Converts a cursor object with a result set in tuples to a list of
    dicts, where the members of the keys are the field names, and the 
values are
    the field values.'''
                                                                                                                            

    fields = map(lambda x: x[0], cursor.description)
                                                                                                                           

    class DictObj(dict):
        '''
        DictObj is a normal dictionary that allows you to access its members
        via ``var[key]`` as well as ``var.key``.
        '''
        def __init__(self,dic):
            dict.__init__(self,dic)
            self.__dict__ = self
                                                                                                                            

    return [DictObj(zip(fields,x)) for x in cursor.fetchall()]




More information about the Python-list mailing list