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: 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)
  • PHP Helpdesk recommendation? (OSS or commercial/hosted)
    ... I've tried a few PHP helpdesk systems, but none match quite my needs. ... Features essential: ... ability for members of the public to email a helpdesk email, ... - ability to refer ticket to other helpdesk administrators ...
    (php.general)
  • Re: NGFS: by submarine?
    ... because that would destroy the sub's ability to do its ... naval newbies really ought to READ some books on naval ... would please stop attacking the new members. ...
    (sci.military.naval)