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'}
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.
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".
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With