简体   繁体   中英

How to iterate over column names and rows at same time

How can I better iterate over "d[field_names[0]] = row[0]" code, so I don't need to have one line for each column? I'm trying to make a code independent from the number of columns in my query.

cursor.execute('SELECT * FROM LOAD_CAPACITOR_EM_DERIVACAO')
rows = cursor.fetchall()
field_names = [i[0] for i in cursor.description]
# Convert query to objects of key-value pairs
objects_list = []
for row in rows:
    d = collections.OrderedDict()
    d[field_names[0]] = row[0]
    d[field_names[1]] = row[1]
    d[field_names[2]] = row[2]
    ...
    d[field_names[34]] = row[34]
    objects_list.append(d)

j = simplejson.dumps(objects_list, use_decimal=True)

If I am understanding correctly you could write a for loop directly after for row in rows: that looks like:

for i in range(0,len(row)):
    d[field_names[i]] = row[i]

You can use the command zip:

for row in rows:
    json_data.append(dict(zip(field_names, row)))

First, I would like to thank you for the answers, as they helped me to reach the final solution.

Below is the code that best dealt with the problem. I want to share so that others who may have the same doubts.

    cursor.execute('SELECT * FROM LOAD_CAPACITOR_EM_DERIVACAO')
    rows = cursor.fetchall()
    field_names = [i[0] for i in cursor.description]

    data_dict = []
    for row in rows:
        data_dict.append(dict(zip(field_names, row)))

    data_json = simplejson.dumps(data_dict, use_decimal=True)

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