4

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

2
  • What's expected in next iterations? You want list of dicts? Commented Jul 6, 2012 at 10:35
  • In the second iteration it will print the x[1] and then x[2] in the same order Commented Jul 6, 2012 at 10:36

1 Answer 1

7

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.