After executing a query statement on a MySQL database connection, I perform:
rows = cursor.fetchall()
This gives an array of arrays. I'd like to have an array of dictionaries, where each dictionary takes its keys from the requested column names of my table and associates the values from the table.
How do I do this?
Well, you forgot to mention which mysql library you're using.
If using oursql (which I recommend, it is certainly the best one), use oursql's DictCursor
. Example:
conn = oursql.connect(...)
curs = conn.cursor(oursql.DictCursor)
If using MySQLdb (why?) Use MySQLdb's DictCursor
. Example:
conn = MySQLdb.connect(..., cursorclass=MySQLdb.cursors.DictCursor)
curs = conn.cursor()
Doing that will give you a cursor that returns dicts for each row. Remember to not have duplicate rownames in your query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With