S
S
SideWest2019-03-31 20:24:54
Python
SideWest, 2019-03-31 20:24:54

How to assign variables in a loop?

I have a loop like this:

for i in ids:
    sql = """SELECT clevel,chel,ctail,cgun,carm,cfoot FROM cats WHERE id=?"""
    cur.execute(sql, [(i)])
    setp = cur.fetchone()
    per_th = {'clevel': setp[0], 'chel': setp[1],'ctail': setp[2],'cgun': setp[3],'carm':setp[4],'cfoot':setp[5]}
    print(per_th)

As a result, I get a dictionary per_thwith values, but I have two people, tell me how I can assign different names to the function in the loop, that is, so that in the output I actually have two dictionaries per_thandper_th2

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-03-31
@SideWest

List to use:

data = []
for i in ids:
    ...
    data.append({
        'clevel': setp[0],
        'chel': setp[1],
        'ctail': setp[2],
        'cgun': setp[3],
        'carm': setp[4],
        'cfoot': setp[5],
    })

Yes, and the dictionary can be easily formed:
con = sqlite3.connect(...)
con.row_factory = lambda c, r: {k: r[i] for i, k, *_ in enumerate(cursor.description)}
cur = con.cursor()

...

data.append(cur.fetchone())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question