SaidAkh SaidAkh - 15 days ago 8
Python Question

Cannot properly modify list of dictionaries

I am trying to supply

initial
(
es_initial
) data to my
formset
, where
initial
is a list of dictionaries. My view.py have following code:

# get all answers by current student
es_answers_by_student = models.Answer.objects.filter(
student__user=request.user
).filter(
question__quiz=step
).filter(
eq_answer_text__icontains=''
)
# supply question prompt to the initial data
for es_question in eqs:
es_dict_for_initial.update({'question': es_question.prompt},)
es_initial.append(es_dict_for_initial.copy())
# supply saved answers
for answer in es_answers_by_student:
for _dict in es_initial:
_dict["eq_answer"] = answer.eq_answer_text

print(es_initial)


Cannot understand, why my last
for
loop always returns same value which is the last value in
es_answers_by_student
queryset

Edit:

After performing the first
for
loop,
es_initial
looks like:

[{'question': 'question text 1'}, {'question': 'question text 2'}]


Here is what I want to accomplish after the second
for
loop:

[{'question': 'question text 1', 'eq_answer': 'answer text 1'},
{'question': 'question text 2', 'eq_answer': 'answer text 2'}]

Answer

I think you just want to loop over the _dicts, and change the answer within the loop, something like this:

for _i, dict in enumerate(es_initial):
    _dict["eq_answer"] = es_answers_by_student[i].eq_answer_text

This implicitly assumes that the ordering of the es_initial and es_answers_by_student is the same, if not you have to find some way to index into the es_answers_by_student list to find the right item.