简体   繁体   中英

How to convert sql query output from list of tuples to a list of dicts in python3 where each dict represents a row in a table?

My code look something like this:

query = """ SELECT col1, col2 FROM table WHERE col3 = value"""
cursor.execute(query)
data = cursor.fetchall()
print(data)

the output will be something similar to:

[('col1[1][0]', 'col2[1][0]'), ('col1[2][1]', 'col2[2][1]')]

but I don't want the output to be like that, I want it to be a list of dicts where every row represents a dict that includes key and values.

so the output would look like:

col1[1][0], col2[1][0]
col1[2][1], col2[2][1]

and without single quotes

Try:

data =[('A', 1), ('B', 3)]

for a, b in data:  # this unpacks the tuple
    print(a, b)

A 1
B 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM