TypeError: tuple indices must be integers, not str

I am trying to extract data from a database and assign them to different lists. this particular error gives me a lot of problems "TypeError: tuple indices must be integers, not str" I tried to convert it to float, etc., but without success.

the code goes 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"]) 

Example output for printing:

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

and this is the exact error I get:

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

Any help would be appreciated! thank you people!

+8
python sql database
source share
2 answers

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

+8
source share

The problem is how do you access row

In particular, row["waocs"] and row["pool_number"] of ocs[row["pool_number"]]=int(row["waocs"])

If you look at the official fetchall() documentation , you will find.

The method retrieves all (or all other) rows of the query result set and returns a list of tuples.

So you need to access the row values ​​using row[__integer__] as row[0]

+1
source share

All Articles