TypeError:元组索引必须是整数,而不是str

Har*_*sti 25 python sql database

我试图从数据库中提取数据并将它们分配给不同的列表.这个特定的错误给了我很多麻烦"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"])
Run Code Online (Sandbox Code Playgroud)

print语句的示例输出如下:

('MA3146', 711L, 81L)
('MA3147', 679L, 83L)
('MA3148', 668L, 86L)
Run Code Online (Sandbox Code Playgroud)

这是我得到的确切错误:

ocs[row["pool_number"]]=int(row["waocs"])
TypeError: tuple indices must be integers, not str
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激 !谢谢大家!

Dan*_*man 34

就像错误说的那样,row是一个元组,所以你不能这样做row["pool_number"].你需要使用索引:row[0].


小智 31

我认为你应该做

for index, row in result: 
Run Code Online (Sandbox Code Playgroud)

如果您想按名称访问。


小智 13

我知道这不是这个问题特有的,但对于任何来自谷歌搜索的人来说:这个错误也是由创建元组而不是字典的对象后面的逗号引起的

>>>dict = {}
>>>tuple = {},
Run Code Online (Sandbox Code Playgroud)

元组

>>>tuple_ = {'key' : 'value'},
>>>type(tuple_)
<class 'tuple'>
Run Code Online (Sandbox Code Playgroud)

字典

>>>dict_ = {'key' : 'value'} 
>>>type(dict_)        
<class 'dict'>
Run Code Online (Sandbox Code Playgroud)


Mir*_*ron 8

只需添加如下所示的参数对我有用。

cursor=conn.cursor(dictionary=True)
Run Code Online (Sandbox Code Playgroud)

我希望这也会有所帮助。


msb*_*msb 6

TL; DR:cursorclass=MySQLdb.cursors.DictCursor在末尾添加参数MySQLdb.connect


我有一个工作代码,并且数据库已移动,我必须更改主机/用户/密码。进行此更改后,我的代码停止工作,并且开始出现此错误。经过仔细检查,我将连接字符串复制粘贴到具有额外指令的位置。旧代码如下所示:

 conn = MySQLdb.connect(host="oldhost",
                        user="olduser",
                        passwd="oldpass",
                        db="olddb", 
                        cursorclass=MySQLdb.cursors.DictCursor)
Run Code Online (Sandbox Code Playgroud)

替换为:

 conn = MySQLdb.connect(host="newhost",
                        user="newuser",
                        passwd="newpass",
                        db="newdb")
Run Code Online (Sandbox Code Playgroud)

最后的参数cursorclass=MySQLdb.cursors.DictCursor是让python允许我使用列名作为索引来访问行。但是糟糕的复制粘贴消除了这种情况,从而产生了错误。

因此,作为已经提出的解决方案的替代方法,您还可以添加此参数并以您原来想要的方式访问行。^ _ ^我希望这对其他人有帮助。

  • 我正在使用 PyMysql,这对我有用。我需要做的唯一改变是 cursorclass=pymysql.cursors.DictCursor 。然后,我可以使用列名。谢谢! (4认同)

Alt*_*yyr 5

问题是你如何访问row

具体来说row["waocs"]row["pool_number"]ocs[row["pool_number"]]=int(row["waocs"])

如果你查找你发现的官方文档fetchall()

该方法获取查询结果集的所有(或所有剩余)行并返回元组列表。

row[__integer__]因此,您必须使用类似的方法访问行的值row[0]