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

Neil Padgen neil.padgen at mon.bbc.co.uk
Tue Apr 29 11:15:39 CEST 2003


<posted & mailed>

On Tuesday 29 April 2003 7:32 am, Carsten Gehling wrote:

> 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.

Take a look at the cursorclass argument:

Python 2.1.3 (#1, Jan 22 2003, 15:10:34) 
[GCC 2.95.3 20010315 (release) [FreeBSD]] on freebsd4
Type "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>> db = MySQLdb.connect(db='fbis_test')
>>> c = db.cursor(cursorclass=MySQLdb.cursors.DictCursor)
>>> c.execute("""SELECT * FROM city""")        
613L
>>> c.fetchone()
{'cou_id': 'SUI', 'id': 'AARAU', 'city_name': 'AARAU'}
>>> 

-- Neil





More information about the Python-list mailing list