5

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....

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You may use zip to club your attribute names and values as:

attribute_names = ["id", "actors", "title"]
values = [10, 20, 30] # row in your case
d = dict(zip(attribute_names, values))

Comments

0

The

cursor = cnx.cursor(dictionary=True)

does not work anymore, we have to pass the class DictCursor as parameter of cnx.cursor

cursor = conn.cursor(pymysql.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.