首页 > 解决方案 > 使用 Python 中的两个键从 MySQL 获取表作为字典

问题描述

我在 MySQL 中有一个如下所示的表:

ID FP VSN HSN 1 xxx 1,5 1,8 2 yyy 1,1 2,1

现在,我正在尝试从 Python 表中检索值并n[ID,/Column Name/]使用 MySQL-Connector将它们保存在字典中

到目前为止,我尝试不成功:

mycursor1=conn.cursor(dictionary=True)

query1 = ("SELECT * FROM `result`")

mycursor1.execute(query1)

columns = mycursor1.description

n = {}

for row in mycursor1:
  for c in columns:
    n[row["ID",c[0]] = float(row[c])
    
mycursor1.close

这种情况下的结果应该如下所示:

n[1,VSN] = 1,5 n[1,HSN] = 1,8 n[2,VSN] = 1,1 n[2,HSN] = 2,1

提前非常感谢!

标签: pythonmysqlspydermysql-connector

解决方案


得到了解决方案:

mycursor1=conn.cursor(dictionary=True)

query1 = ("SELECT * FROM `result`")

jt = [i[0] for i in mycursor.description]

mycursor1.execute(query1)

columns = mycursor1.description

n = {}

for row in mycursor1:
  for c in jt:
    n[row["ID"],c] = float(row[c])
    
mycursor1.close


推荐阅读