我有一个包含20列的表格,我使用此代码将特定电影的每个字段作为字典:
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
列名称将是字典键。是否有更短的方式来存档相同的结果? 20行变量看起来很糟糕......
答案 0 :(得分:3)
答案 1 :(得分:0)
您可以使用zip
将您的属性名称和值标记为:
attribute_names = ["id", "actors", "title"]
values = [10, 20, 30] # row in your case
d = dict(zip(attribute_names, values))