4
votes

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?

1
it gives a list of tuples. Arrays are not involved. Also there are no maps. Those are dicts; - nosklo

1 Answers

15
votes

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.