38

I have a MySQL table on which I'm executing SELECT statements within Python.

Is there anything out of the Python MySQLdb API that will, via the cursor, output an array of dictionaries whose keys are the column names (and values are those in the returned rows)?

4
  • 2
    I guess it's a duplicate of this one: stackoverflow.com/questions/2180226/… Commented Sep 1, 2011 at 9:06
  • Maybe you need dictionary cursor?cursor = conn.cursor (MySQLdb.cursors.DictCursor) Commented Sep 1, 2011 at 9:07
  • If you want, make this link an answer which I'll accept. Commented Sep 1, 2011 at 9:07
  • 1
    If you don't have enough reputation to vote to close, flag the answer, select "other", and just put in "duplicate" and the URL. Don't post an answer that is just a link to a duplicate. Commented Sep 1, 2011 at 9:36

2 Answers 2

52

For me, this worked:

cursor = conn.cursor(dictionary=True)

Detailed example:

import mysql.connector # pip install mysql-connector-python

conn = mysql.connector.connect(host="localhost", user="user", passwd="pass", database="dbname")
cursor = conn.cursor(dictionary=True)
sql = "SELECT * FROM `table` WHERE 1"
cursor.execute(sql)
rows = cursor.fetchall()
for row in rows:
    row["col"]
Sign up to request clarification or add additional context in comments.

2 Comments

it is working with mysql.connector library.
looks like it doesn't even need the foreach!
39

Please use dictionary cursor:

cursor = conn.cursor (MySQLdb.cursors.DictCursor)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.