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

18 人关注

我很难将我的查询结果转换为 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

但当我打印它时,它返回的信息是正确的,而所有的东西都是不符合顺序的,而且它只显示一条记录。

{'StudentLastName': Jane, StudentNum: 'Smith  ', StudentFirst Name: '1612'}
    
python
sql
dictionary
Lynn
Lynn
发布于 2015-02-27
8 个回答
alecxe
alecxe
发布于 2020-07-01
已采纳
0 人赞同

你可以使用 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()]

Note: use zip() in place of itertools.izip() on Python3.

对于最后一行,你可以用 for row in cursor 代替 cursor.fetchall() ,得到同样的结果。
看起来 itertools.izip 在Python 3中不可用,但简单的 zip 可以使用。
在Python 3中,内置的zip与2.x中的izip做同样的工作(返回一个生成器而不是一个列表),但由于是内置函数,所以速度稍快。
Ri1a
模块'itertools'没有'zip'成员
@RickLan 当然,为python3添加了一个注释。
pablo
pablo
发布于 2020-07-01
0 人赞同

这时你可能解决了你的问题,但无论如何。

如果你使用mysql,我想这就是你需要的。

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

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

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

Hope it helps

Anuja
Anuja
发布于 2020-07-01
0 人赞同

也许这可以提供帮助。 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
    
bonifacio_kid
bonifacio_kid
发布于 2020-07-01
0 人赞同

I hope this will help...

def all_students():
    qu= "select * from students"
    students = crs.execute(qu)
    students_data = []
    for row in students:
        student= {"StudentNum":row[0], "StudentLastName":row[2], "StudentFirst Name":row[3}
         students_data.append(student)
    final_data["students_info"] = students_data
    return final_data
    
Lien Chu
Lien Chu
发布于 2020-07-01
0 人赞同

为了回答原来的问题,你可以尝试以下方法(不需要通过 crs 进行循环,你可以直接使用 crs.fetchall() ,鉴于 表的内容适合你的记忆 ):

result_list_of_dict = [{'StudentNum': col1, 'StudentLastName': col2, 'StudentFirst Name': col3} for (col1, col2, col3) in crs.fetchall()]

结果 result_list_of_dict 是一个字典列表,每个元素(字典)都有你指定的3个键('StudentNum'、'StudentLastName'和'StudentFirstName'),其相关值从SQL表中提取。

To extend:

基本上, cursor.fetchall() 返回一个图元的列表,所以只要你列出所有应该返回的值,你就可以随意修改前面的部分。例如,下面的代码适用于一个有5列的表,你想只提取前3列。

result_dict = {col1:(col2, col3) for (col1, col2, col3, col4, col5) in cursor.fetchall()}

在这种情况下,产生的 result_dict 将是一本字典。

你能解释一下为什么会这样吗? 这段代码在做什么,它是如何回答这个问题的?
我做了修改,以增加与原问题的相关性
ARZ
只有这个答案会返回一个字典;其他的答案会返回字典的列表。
Felipe Valdes
Felipe Valdes
发布于 2020-07-01
0 人赞同

得票最多的答案是针对Python2的,这里是针对Python3的答案。

import itertools
desc = cursor.description
column_names = [col[0] for col in desc]
data = [dict(zip(column_names, row))  
        for row in cursor.fetchall()]
    
Stephen Ostermiller
Stephen Ostermiller
发布于 2020-07-01
0 人赞同

如果你期望你的查询能返回一个 single result 而你想在一个字典中按列名获得所有的值,你可以使用。

def querySingle(sql, args):
        cursor = cnx.cursor()
        cursor.execute(sql, args)
        for row in cursor:
            return dict((column[0],row[index]) for index, column in enumerate(cursor.description))
        return {}
    finally:
        cursor.close()

例如querySingle("SELECT * FROM animals WHERE id=%s", [1])可能会返回。

"id": 1, "name": "Bob", "type": "Alligator"