Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list value gets overwritten, why?

Tags:

python

django

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?

like image 588
Prometheus Avatar asked Dec 16 '22 01:12

Prometheus


2 Answers

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]
like image 50
StoryTeller - Unslander Monica Avatar answered Dec 21 '22 22:12

StoryTeller - Unslander Monica


You're appending a dictionary, which is a mutable object.

So after your loop, data contains two references to the same dictionary. You'll have to append new dictionaries in each iteration, e.g. like this:

for item in recipients:
    data.append(dict(recipient_id = item.pk))
like image 44
sebastian Avatar answered Dec 21 '22 23:12

sebastian