Python list value gets overwritten, why?

django, python

Solution

`this_tem` is a reference to a single object (a dict) which you repeatedly modify and append in your loop. You overwrite the value of that key in the loop.

You need to create a new dict each iteration:

data = []

for item in recipients:
    this_tem = {}
    this_tem['recipient_id'] = item.pk
    data.append(this_tem)

Edit As Grijesh Chauhan graciously pointed out, the expression and loop can be simplified vis a vie a list comprehension:

data = [{'recipient_id': item.pk} for item in recipients]

Problem

I have a recipients query containing two recipients with the ID 1 and 2: I loop over each one to build json output: ``` data = [] this_tem = {} for item in recipients: this_tem['recipient_id'] = item.pk data.append(this_tem) return HttpResponse(json.dumps(data), mimetype='application/json') ``` This gives me: ``` [ { "recipient_id": 2, }, { "recipient_id": 2, } ] ``` As you can see it should be `recipient_id 1` and `recipient_id 2` however, my loop overwrites the value, why?

Original source