我正在尝试从数据库中提取数据并将它们分配给不同的列表。这个特定的错误给我带来了很多麻烦“TypeError:元组索引必须是整数,而不是str”我尝试将其转换为float等,但没有成功。
代码如下
conn=MySQLdb.connect(*details*)
cursor=conn.cursor()
ocs={}
oltv={}
query="select pool_number, average_credit_score as waocs, average_original_ltv as waoltv from *tablename* where as_of_date= *date*"
cursor.execute(query)
result=cursor.fetchall()
for row in result:
print row
ocs[row["pool_number"]]=int(row["waocs"])
oltv[row["pool_number"]]=int(row["waoltv"])
print 语句的示例输出如下:
('MA3146', 711L, 81L)
('MA3147', 679L, 83L)
('MA3148', 668L, 86L)
这是我得到的确切错误:
ocs[row["pool_number"]]=int(row["waocs"])
TypeError: tuple indices must be integers, not str
任何帮助,将不胜感激!感谢人们!
原文由 Harsha Jasti 发布,翻译遵循 CC BY-SA 4.0 许可协议
就像错误所说的那样,
row
是一个元组,所以你不能做row["pool_number"]
。您需要使用索引:row[0]
。