Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python mysql.connector - Correct way to retrive a row as dictionary

I've a table with 20 columns, I use this code to get every field of a specific movie as a dictionary:

import mysql.connector

def getMovie(id):
   movie = {}
   cnx = mysql.connector.connect(**config)
   cursor = cnx.cursor()
   query = ('SELECT * FROM movies WHERE id = %s') % id
   cursor.execute(query)
   for row in cursor:
      movie['id'] = row[0]
      movie['actors'] = row[1]
      movie['title'] = row[2]
      # and so on for 20 lines
    return movie

Column names would be the dictionary keys. Is there a shorter way to archive the same result? 20 lines of variables are really bad looking....

like image 229
Hyperion Avatar asked Jan 04 '23 13:01

Hyperion


1 Answers

You can pass dictionary=True to the cursor to get it to return a dictionary.

cursor = cnx.cursor(dictionary=True)

See the docs on MySQLCursorDict.

like image 95
Daniel Roseman Avatar answered Jan 07 '23 03:01

Daniel Roseman