python - 遍历字典列表并创建新的字典列表

标签 python dictionary

我的数据如下。

[
    {
        "id" : "123",
        "type" : "process",
        "entity" : "abc"
    },
    {
        "id" : "456",
        "type" : "product",
        "entity" : "ab"
    }

]

我正在循环获取 id 和实体

for test in serializer.data:
    qaResultUnique['id'] = test['id']
    qaResultUnique['entity'] = test['entity']
    uniqueList.append(qaResultUnique)

但是得到错误的输出,因为两次只得到第二个字典。

[
        {
            "id" : "456",
            "entity" : "ab"
        },
        {
            "id" : "456",
            "entity" : "ab"
        }

    ]

我做错了什么,请帮助。

最佳答案

您正在重用 qaResultUnique 字典对象。每次在循环中创建一个字典:

for test in serializer.data:
    qaResultUnique = {}
    qaResultUnique['id'] = test['id']
    qaResultUnique['entity'] = test['entity']
    uniqueList.append(qaResultUnique)

或更简洁地表达:

uniqueList = [{'id': test['id'], 'entity': test['entity']} for test in serializer.data]

关于python - 遍历字典列表并创建新的字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22253055/

相关文章:

Java - 如何通过键获取存储在HashMap中的键对象(或条目)?

python - 在 Google App Engine 上用 Python 验证 android 应用内购买消息的签名

python - 在 Python 中使用 SocketHandler 记录时捕获错误

python - 以相反顺序迭代列表并创建动态字典

python - 在字典中对小数进行排序

javascript - 将 javascript 字典转换为 JSON 格式

python - 成功部署后,Google App Engine 不运行任何实例

python - 在 SPSS/Python 中运行总计

python - 根据有序列表中的键对字典值进行排序

list - "bad words"过滤器