close

How to convert SQL query results into a python dictionary

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to convert SQL query results into a python dictionary in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to convert SQL query results into a python dictionary?

  1. How to convert SQL query results into a python dictionary?

    You can use cursor.description to get the column names and “zip” the list of column names with every returned row producing as a result a list of dictionaries:

  2. convert SQL query results into a python dictionary

    You can use cursor.description to get the column names and “zip” the list of column names with every returned row producing as a result a list of dictionaries:

Method 1

You can use cursor.description to get the column names and “zip” the list of column names with every returned row producing as a result a list of dictionaries:

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.

Method 2

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

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read