I am newbie in python, want to create a new dictionary in a for loop. For example:
for x in data:
a_data = x.a
model_obj = modelname.objects.get(id=x.b)
b_data = model_obj.address
c_data = x.c
d_data = x.d
I want to create a dictionary which should work as for the first iteration
'a_data': x.a
'b_data':model_obj.address
'c_data':x.c
'd_data':x.d
and so on for the next iteration. I think we can works with : list of dictioanry
or dictionary of dictionary
. I even don't know which one is better. I have to render this data to a template.
Any help will be appreciable :)
Is this what you want?
listofobjs = []
for x in data:
d = {
'a_data': x.a,
'b_data':model_obj.address,
'c_data':x.c,
'd_data':x.d,
}
listofobjs.append(d)
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.