如何将SQL查询结果转换为python字典

Lyn*_*ynn 7 python sql dictionary

我有difficuty将我的结果从查询转换为python字典.每个字典应该代表一个学生,键是列名,值是查询中的相应值,到目前为止,这是我提出的:

def all_students():
    qu= 'select * from students'
    crs.execute(qu)
    for row in crs:
        student= {"StudentNum":row[0], "StudentLastName":row[2], "StudentFirst Name":row[3}
    return student
Run Code Online (Sandbox Code Playgroud)

但是当我打印它时,它返回正确的信息,一切都不正常,它只显示一条记录:

{'StudentLastName': Jane, StudentNum: 'Smith  ', StudentFirst Name: '1612'}
Run Code Online (Sandbox Code Playgroud)

ale*_*cxe 11

您可以使用cursor.description获取列名称并使用每个返回的行"压缩"列名列表,从而生成字典列表:

import itertools

desc = cursor.description
column_names = [col[0] for col in desc]
data = [dict(itertools.izip(column_names, row))  
        for row in cursor.fetchall()]
Run Code Online (Sandbox Code Playgroud)

  • 对于最后一行,您可以执行 `for row in cursor` 而不是 `cursor.fetchall()` 并获得相同的结果。 (2认同)
  • 看起来像`itertools.izip`在Python 3中不可用,简单的`zip`虽然有效 (2认同)

小智 7

此时您可能已经解决了您的问题,但无论如何:

如果您使用的是 mysql,我认为这就是您所需要的:

https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html

根据定义:MySQLCursorDict 游标将每一行作为字典返回。每个字典对象的键是 MySQL 结果的列名。

所以你必须只设置 crs = cnx.cursor(dictionary=True)

希望能帮助到你


小智 5

也许这可以帮助: http: //codetrace.blogspot.com/2010/05/convert-query-result-to-dictionary-like.html

query_result = [ dict(line) for line in [zip([ column[0] for column in crs.description], row) for row in crs.fetchall()] ]

print query_result
Run Code Online (Sandbox Code Playgroud)