By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,593 Members | 1,575 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,593 IT Pros & Developers. It's quick & easy.

Better access to database search results

P: n/a
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():

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):
self.__dict__ = self
return [DictObj(zip(fields,x)) for x in cursor.fetchall()]

Jul 18 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.