Function to convert fetchone() result from a list to a dictionary

Carsten Gehling carsten at sarum.dk
Tue Apr 29 04:28:14 EDT 2003


I'm fairly new to Python, and have yet to discover alle the little
details, that may make my programs look leaner and perhaps become
faster...

Using the DB API to access databases, I've stumbled upon what I would
call a shortcoming in the API (IMHO). All the fetch commands return
the results as lists instead of dictionaries.

So I've made my own conversion function, using the cursor.description
attribute. It's pretty straight-forward, so I was wondering, if
there's a smarter way to do this?

The function is like this:
-------------------------------
def cursor_fetchone_dict(cursor):
	result = cursor.fetchone()
	if result == None: return None
	result_dict = {}
	for i in range(len(result)):
		result_dict[cursor.description[i][0]] = result[i]
	return result_dict
-------------------------------

Example of use:
-------------------------------
import MySQLdb

def cursor_fetchone_dict(cursor):
	result = cursor.fetchone()
	if result == None: return None
	result_dict = {}
	for i in range(len(result)):
		result_dict[cursor.description[i][0]] = result[i]
	return result_dict

con = MySQLdb.connect(host='localhost', port=3306, user='xxxxx',
passwd='xxxxxx', db='xxxxxx')

cursor = con.cursor()
sql = "select * from sometable "
cursor.execute(sql)

result = cursor_fetchone_dict(cursor)
print result
-------------------------------

Any comments are welcome, TIA

- Carsten

 





More information about the Python-list mailing list