简体   繁体   中英

Error occurs when I try to mount an array inside the for loop in python

Error occurs when I try to mount an array inside the for loop in python

I am in a transition of language, so small doubts arise in the day to day.

TypeError: list indices must be integers or slices, not str

data = []
for index, linha in enumerate(reg2):
    data['lista'][index]['name'] = linha.name,
    data['lista'][index]['document'] = linha.document

    data.append(data)

You need a dictionary of lists of dictionaries, not a list. Do not enumerate anything; in fact, you do not even need a loop:

docs = [{'name': linha.name, 'document': linha.document} for linha in reg2]
data = {'lista' : docs}

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