SQLクエリの結果をPython辞書に変換する方法 質問する

SQLクエリの結果をPython辞書に変換する方法 質問する

クエリの結果を Python 辞書に変換するのに苦労しています。各辞書は 1 人の学生を表すことになっており、キーは列名、値はクエリからの対応する値です。これまでのところ、次のような結果になりました。

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

しかし、印刷すると、正しい情報が返され、すべてが順序どおりに表示されず、1 つのレコードのみが表示されます。

{'StudentLastName': Jane, StudentNum: 'Smith  ', StudentFirst Name: '1612'}

ベストアンサー1

cursor.description列名を取得し、返された行ごとに列名のリストを「圧縮」して、結果として辞書のリストを生成するために使用できます。

desc = cursor.description
column_names = [col[0] for col in desc]
data = [dict(zip(column_names, row))  
        for row in cursor.fetchall()]

注: Python2 ではitertools.izipの代わりに使用します。zip()

おすすめ記事