python - 用 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`
如您所见,仅保存整数,但我需要浮点数。谢谢您的帮助!
解决方案
这可能是因为您如何输出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
,这是用来显示浮点数的
推荐阅读
- recursion - Rust - 在递归函数中收集 Vec 的切片
- python - 将循环输出转换为列表 python
- c++ - Visual Studio (C++) 中的构建错误(文件/目录丢失?)
- node.js - MongoDB,在数组中填充嵌套对象
- ansible - 角色内的 Ansible 复制模块
- web - 为什么我新创建的 Heroku 应用打不开?
- ruby-on-rails - Rails 模型的多个嵌套路由
- java - 如何从 Web 套接字 simpUser 获取 @AuthenticatedPrincipal?
- python - 将索引范围分配给原始数据帧时,不会保存使用 iloc 替换数据帧中的一系列行
- angular - 安装 Tailwind 后尝试运行 ng 时,Angular 模块构建失败