Python: use mysqldb to import a MySQL table as a dictionary?

If you need to use more cursors and only one needs to be MySQLdb.cursors.DictCursor you can do:

import MySQLdb
db = MySQLdb.connect(host='...', db='...', user='...t', passwd='...')

list_cursor = db.cursor()
dict_cursor = db.cursor(MySQLdb.cursors.DictCursor)

I think with mysql.connector is much more easier to convert a select to a dict than MySQLdb, and also more Python version supported:

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"]

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)