Better access to database search results



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()]

.



Relevant Pages

  • object.*
    ... I think there should be an ability in python to write something like ... "object.*" which should return a dictionary object containing all the ... members and their values for the given object. ...
    (comp.lang.python)
  • Re: Hops contest winners for Wimbledon
    ... > Whisper and Jaros (the latter perhaps tongue in cheek) often have ... > touted the ability to earn a perfect, ... Sampras and Mac videos are played all day long while members sit ... quickly as they play endless variations on Whisper's favorite, ...
    (rec.sport.tennis)
  • Re: Leaving rasfc
    ... assumption that hiring is only done on the basis of ability. ... rational discrimination, given imperfect information about ability. ... rational thing to do is to hire only members of the group that's better. ...
    (rec.arts.sf.misc)
  • Re: Restrict Outbound Only SMTP by OU
    ... To restrict outbound mail you can create an SMTP connector and configure ... "Greg Baker" wrote in message ... > like to Restrict the OU member's ability to send email ... > The additional request has been to allow the OU members ...
    (microsoft.public.exchange.admin)
  • Managed By option doesnt let uses manage distribution list
    ... Is there a better way to allow users just the ability to manage the ... Click the Security tab, ... In the Permissions box, click Allow Read Members, and then click ...
    (microsoft.public.exchange2000.admin)