Amit Pal
Amit Pal

Reputation: 11052

How to create a dictionary in a for loop in python?

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 :)

Upvotes: 4

Views: 17854

Answers (1)

Rohan
Rohan

Reputation: 53326

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)

Upvotes: 7

Related Questions