Create dictionary from mysql AttributeError: 'tuple' object has no attribute 'name'

Create dictionary from mysql AttributeError: 'tuple' object has no attribute 'name'

尝试使用两列从 mysql 数据库创建字典,然后为其分配一个变量,不断获取回溯 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)

row 在你的例子中是元组 (server_id, name),这就是调用 row.name 不起作用的原因 - 元组不支持命名属性。尝试 row[0]row[1] 或解压元组:

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

print(d)

行是元组,而不是每列具有命名属性的对象。在您的情况下,name 是索引 1 处的值,server_id 是索引 0:

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

print(d)

您可以使用元组赋值让自己更轻松:

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

print(d)

但是,因为您想使用第一个元素作为键,第二个元素作为值,您可以使这更简单,只需将光标直接传递给 dict() 调用:

d = dict(cursor)

这会拉入每个 (server_id, name) 元组并将其转换为新字典中的键值对。

请注意,在上面的示例中,我特意为字典使用了名称 d。如果我改用 dict,那么我们就不能再使用 dict(cursor)