0

Trying to create a dictionary from a mysql database using two columns and then assign it a variable keep getting the traceback AttributeError: 'tuple' object has no attribute 'name'.

cursor = conn.cursor()

cursor.execute("select server_id, name from servers")

dict = {}
for row in cursor:
    dict[row.server_id] = row.name

    print(dict)
1
  • I'd advise from not naming variables after reserved words in python such as dict=... as it risks overwriting functionality and ending up with very spooky results Commented Oct 16, 2018 at 18:26

2 Answers 2

1

Rows are tuples, not objects with named attributes per column. In your case, name is the value at index 1, the server_id the value at index 0:

d = {}
for row in cursor:
    d[row[0]] = row[1]

print(d)

You could make this easier on yourself by using tuple assignments:

d = {}
for server_id, name in cursor:
    d[server_id] = name

print(d)

However, because you want to use the first element as the key, and the second as the value, you could make this even simpler and just pass the cursor directly to a dict() call:

d = dict(cursor)

This pulls in each (server_id, name) tuple and turns it into a key and value pair in a new dictionary.

Note that I deliberately used the name d for the dictionary in the above examples. Had I used dict instead, then we couldn't use dict(cursor) anymore!

Sign up to request clarification or add additional context in comments.

Comments

0

row in your case is tuple (server_id, name), that's why calling row.name won't work - tuples don't support named attributes. Try row[0] and row[1] instead or unpack tuple:

d = {}
for row in cursor:
    server_id, name = row
    d[server_id] = name

print(d)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.