Python列表值被覆盖,为什么? [英] Python list value gets overwritten, why?
问题描述
我有一个收件人查询,其中包含两个具有 ID 1和2 的收件人:我遍历每一个以构建json输出:
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')
这给了我
[
{
"recipient_id": 2,
},
{
"recipient_id": 2,
}
]
如您所见,它应该是 recipient_id 1
和 recipient_id 2
,但是,我的循环会覆盖该值,为什么?
As you can see it should be recipient_id 1
and recipient_id 2
however, my loop overwrites the value, why?
推荐答案
this_tem
是对单个对象(字典)的引用,您可以对其进行反复修改并附加到循环中.您将在循环中覆盖该键的值.
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)
修改
正如Grijesh Chauhan亲切指出的那样,相对于列表理解,可以简化表达式和循环:
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]
这篇关于Python列表值被覆盖,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!