Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: tuple indices must be integers, not str

I am trying to pull data from a database and assign them to different lists. This specific error is giving me a lot of trouble "TypeError: tuple indices must be integers, not str" I tried converting it to float and etc, but to no success.

The code goes as below

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"]) 

Sample output of print statement is as follows :

('MA3146', 711L, 81L) ('MA3147', 679L, 83L) ('MA3148', 668L, 86L) 

And this is the exact error I am getting:

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

Any help would be appreciated! Thanks people!

like image 273
Harsha Jasti Avatar asked Feb 12 '16 10:02

Harsha Jasti


People also ask

How do you fix tuple indices must be integers or slices not str?

The Python "TypeError: tuple indices must be integers or slices, not str" occurs when we use a string instead of an integer to access a tuple at a specific index. To solve the error, use the int() class to convert the string to an integer, e.g. my_tuple[int(my_str)] .

How do you fix tuple index out of range?

An alternative approach to handle the "IndexError: tuple index out of range" exception is to use a try/except block. Copied! We tried accessing the tuple item at index 100 which raised an IndexError exception. You can handle the error or use the pass keyword in the except block.

What is tuple index?

The tuple index() method helps us to find the index or occurrence of an element in a tuple. This function basically performs two functions: Giving the first occurrence of an element in the tuple. Raising an exception if the element mentioned is not found in the tuple.

What does tuple object is not callable mean?

The Python "TypeError: 'tuple' object is not callable" occurs when we try to call a tuple as if it were a function. To solve the error, make sure to use square brackets when accessing a tuple at a specific index, e.g. my_tuple[0] . Here is one example of how the error occurs.


2 Answers

Like the error says, row is a tuple, so you can't do row["pool_number"]. You need to use the index: row[0].

like image 113
Daniel Roseman Avatar answered Sep 20 '22 16:09

Daniel Roseman


I think you should do

for index, row in result:  

If you wanna access by name.

like image 22
Sitti Munirah Abdul Razak Avatar answered Sep 21 '22 16:09

Sitti Munirah Abdul Razak