tags:

views:

208

answers:

1

Anyone know how I can use mysqldb to turn a MySQL table, with lots of rows, into a list of dictionary objects in Python?

I mean turning a set of MySQL rows, with columns 'a', 'b', and 'c', into a Python object that that looks like this:

data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 }, { 'a':'Q', 'b':(1, 4), 'c':5.0 }, { 'a':'T', 'b':(2, 8), 'c':6.1 } ]

Thanks :)

+3  A: 

MySQLdb has a separate cursor class for this, the DictCursor. You can pass the cursor class you want to use to MySQLdb.connect():

import MySQLdb.cursors
MySQLdb.connect(host='...', cursorclass=MySQLdb.cursors.DictCursor)
Thomas Wouters
Perfect, thank you! For anyone else reading, you also need to add "import MySQLdb.cursors" to the top of your Python script to include it.
AP257
You must have missed the fact that I actually included the MySQL.cursors import right there in the code snippet.
Thomas Wouters
For anyone else reading, you also need to add `MySQLdb.connect(host='...', cursorclass=MySQLdb.cursors.DictCursor)` somewhere after `import MySQLdb.cursors` for the snippet to work. (sorry, I couldn't resist! :D)
Cawas