Python 列表值被覆盖,为什么?

标签 python django

我有一个收件人查询,其中包含两个收件人,ID 为 1 和 2: 我遍历每一个以构建 json 输出:

    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 1recipient_id 2 但是,我的循环覆盖了该值,为什么?

最佳答案

this_tem 是对您在循环中反复修改和追加的单个对象(字典)的引用。您在循环中覆盖该键的值。

每次迭代都需要创建一个新的字典:

data = []

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

编辑
正如 Grijesh Chauhan 慷慨地指出的那样,可以通过列表理解来简化表达式和循环:

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

关于Python 列表值被覆盖,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21702528/

相关文章:

python - 如何在Python中发送带有路径参数的GET请求

python - 如何创建一个接受字典输入的函数?

python - Django 自定义 order_by

python - pygame安装: sdl-config command not found

django 表单 error_class

python - 从列表和字典中抓取网页

python - 如何将一个函数的重写一般地应用于 python 中的多个类?

css - Django Compressor 不重新生成压缩的 CSS

python - Facebook opengraph 使用 Python Django

python - 在创建实例时创建配置文件模型