HelloWorld
HelloWorld

Reputation: 388

tuple indices must be integers or slices, not str

I'm running into this issue when using mySQL. My result = [{'email': '[email protected]'}] but I'm getting an TypeError: tuple indices must be integers or slices, not str when I'm doing email = results[0]['email']

The thing is when I'm running this locally it works perfectly. How do I get [email protected]?

users is a table

Code:

cursor.execute('SELECT email FROM users WHERE username = %s', [attempted_username])
email_dict = cursor.fetchall()
print(email_dict)
session['email'] = email_dict[0]['email']

Console:

[{'email': '[email protected]'}]

Upvotes: 3

Views: 13454

Answers (4)

Bruno Ribeiro
Bruno Ribeiro

Reputation: 1410

The dictionary=True parameter in cursor() method call enables the use of a dictionary to represent rows instead of tuples.

cursor = connection.cursor(dictionary=True)
cursor.execute('SELECT email FROM users WHERE username = %s LIMIT 1', (attempted_username,))
email_dict = cursor.fetchone()
print(email_dict)
session['email'] = email_dict['email']

Upvotes: 1

Fábio Dias
Fábio Dias

Reputation: 686

This can work with extras.DictCursor:

cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
for fields in cur:
   print(fields['column_name'])

Upvotes: 2

Laurent LAPORTE
Laurent LAPORTE

Reputation: 22942

The result of fetchall is a list of tuples, not a list of dict.

Your query result have only one field: email at index 0.

You can rewrite your code like this:

rows = cursor.fetchall()
for row in rows:
    email = row[0]

Or, in your situation where there is only one result:

session['email'] = rows[0][0]

I think, you can also use:

row = cursor.one()

Upvotes: 2

Mureinik
Mureinik

Reputation: 310993

fetchall returns a list of tupples. You need to access it by the column's ordinal, not its name:

session['email'] = email_dict[0][0]

Upvotes: 1

Related Questions