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!
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)] .
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.
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.
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.
Like the error says, row
is a tuple, so you can't do row["pool_number"]
. You need to use the index: row[0]
.
I think you should do
for index, row in result:
If you wanna access by name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With