InvalidSyntax
InvalidSyntax

Reputation: 9495

Why am I getting a "TypeError: string indices must be integers" error on strings

I am using Python to query my DB and printing out the values line by like as follows:

cursor.execute("SELECT id, name FROM playlists")
lists = cursor.fetchall()

for index, list in lists:
    print("{0} - {1}".format(list['id'], list['name']))

However this beings back the following error when executed:

TypeError: string indices must be integers

Upvotes: 0

Views: 90

Answers (1)

Gino Mempin
Gino Mempin

Reputation: 29570

The method fetchall() returns a list of tuples representing the rows, where each tuple contains the values for each column. When you did for index, list in lists, you are already accessing each tuple and unpacking them into index and list respectively.

I assume you have columns 'id' and 'name'.
If you just want to print them:

for index, mylist in lists:
    print("{0} - {1}".format(index, mylist))

or

rows = cursor.fetchall()

for row in rows
    print("{0} - {1}".format(row[0], row[1]))

or with f-strings:

rows = cursor.fetchall()

for index, mylist in rows
    print(f"{index} - {mylist}")

As I mentioned, it is bad to name your variables same as built-in types and methods.
Don't use list as a variable name.

Upvotes: 1

Related Questions