Python: how to get the rows of a MySQL query in dictionary format using MySQL Connector

In this article we will see how to get the rows of a MySQL query in dictionary format using MySQL Connector with Python.

It basically involves specifying the boolean parameter dictionary when instantiating a cursor.

import mysql.connector

db = mysql.connector.connect(host='localhost',
                                 user='user',
                                 password='password',
                                 database='database')
query = 'SELECT * FROM posts'
cursor = db.cursor(dictionary=True)
cursor.execute(query)
rows = cursor.fetchall()

print(rows)                                 
Back to top