Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert SQL query results into a python dictionary

Im having difficuty converting my results from a query into a python dictionary. Each dictionary is supposed to represent one student, the keys are the column name and the values are the corresponding values from the query, so far this is what I've come up with:

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

But when i print it , it returns in correct information and everything is out of order, and it only displays one record :

{'StudentLastName': Jane, StudentNum: 'Smith  ', StudentFirst Name: '1612'}
like image 363
Lynn Avatar asked Feb 27 '15 00:02

Lynn


People also ask

How do you store SQL query results in a variable in Python?

First of all, c. fetchall() retrieves ALL the results from your query, we'll put them in a variable called rows . Then we create a iterator (the thing you tried to do with the while loop) by doing for row in rows . Then we simply print each row.

How do I convert a data table to a dictionary in Python?

First, search for the table header and split on spaces to define a list. Second, search for the virtual drive with "number/number" and split on spaces to define the second list. However, 'Size' will need to be special as it will need to ignore the space between number and "TB".

How do you create a dictionary in Python?

To create a Python dictionary, we pass a sequence of items (entries) inside curly braces {} and separate them using a comma ( , ). Each entry consists of a key and a value, also known as a key-value pair. Note: The values can belong to any data type and they can repeat, but the keys must remain unique.

Can you turn a string into a dictionary Python?

You can easily convert python string to the dictionary by using the inbuilt function of loads of json library of python. Before using this method, you have to import the json library in python using the “import” keyword.


1 Answers

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.

like image 162
alecxe Avatar answered Sep 18 '22 12:09

alecxe