Python 和 PYODBC。我无法将结果读入正确的字典

Python and PYODBC. I'm unable to read results to a proper dictionary

我似乎无法将结果读入字典。它一直以列表而不是字典的形式给我结果。

这是我的代码:

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=' + server + ';DATABASE=' + database + ';UID=' + username + ';PWD=' + password)
cursor = cnxn.cursor()    

# Sample select query
cursor.execute("SELECT TOP 500 [OrderNumber], [ProductID] FROM [dbo].[Results]")    

columns = [column[0] for column in cursor.description]    

results = [dict(zip(columns, row)) for row in cursor.fetchall()]    

for x in results.values():
    print(x)

它给我的是一个列表,而不是字典。这是我得到的:

[{'OrderNumber': '123456789', 'ProductID': '11111111'}, {'OrderNumber': '234567891', 'ProductID': '222222'}

这不是我需要的字典。我尝试像阅读字典一样阅读它,但 Python 一直告诉我我正在查看列表。查看 values() 或 items(),它给我一个列表对象没有属性 'values' AttributeError: 'list' object has no attribute 'values'

的错误

此外,如何让我的结果成为实际订单号作为productID的关键?类似于:

{"123456789":"11111111", "234567891":"22222222"}

我确实尝试了其他方法来获取它,但我仍然得到一个列表,而不是实际的字典。我试过了:

    for row in cursor.fetchall():
        results.append(dict(zip(columns,row)))

您将 results 作为新列表返回,因为您使用的是列表理解。你应该尝试使用类似字典理解的东西,或者甚至只是使用 for 循环手动创建一个字典:

results = {k:v for (row[columns.index('OrderNumber')], row[columns.index('ProductID')]) in cursor.fetchall()}

或更简单:(因为我们已经知道这些列中的每一列都有这些索引

 results = {k:v for (row[0], row[1]) in cursor.fetchall()}

这与 运行:

相同
columns = [column[0] for column in cursor.description] 
results = {} 
for row in cursor.fetchall():
    results[row[0]] = row[1]  # short version
    # or use this instead if you have a lot of columns and don't remember index
    results[row[columns.index('OrderNumber')]] = row[columns.index('ProductID')]