首页 > 解决方案 > 用 Python 将浮点数从 MySQL 读入字典

问题描述

我正在尝试从我的 MySQL 数据库中读取值,并使用 mysql 连接器将它们存储在 Python 中的字典中。我的数据库有 3 列 ( MDK, JT, tp),如下所示:

`1   1  1.9
 1   2  1.77
 1   3  2.5
 2   1  1.9
 2   2  1.77
 2   3  2.5 `

到目前为止,我尝试过:

import mysql
import mysql.connector

conn = mysql.connector.connect(....)

mycursor = conn.cursor(dictionary = True)

query = ("SELECT * FROM 'test'")

mycursor.execute(query)

tp = {}

for row in mycursor:
  tp[row["MDK"], row["JT"]] = float(row["tp"])
  
mycursor.close()
  

目前保存在 dict 中的值是:

`tp[1,1] = 1
 tp[1,2] = 1
 tp[1,3] = 2
 tp[2,1] = 1
 tp[2,2] = 1
 tp[2,3] = 2`

如您所见,仅保存整数,但我需要浮点数。谢谢您的帮助!

标签: pythonmysqlmysql-connector

解决方案


这可能是因为您如何输出tp. 您确定您不使用%d显示浮点值吗?

换句话说,尝试运行 print(["tp[%d,%d]=%4.2f\n"%(i, j, tp[i,j]) for i in range(1, 3) for j in range(1, 4)]) Note the %4.2f,这是用来显示浮点数的


推荐阅读