You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理键不同的字典列表:合并转换后的缺失项

问题解决:合并字典列表并补充缺失条目

先看你给出的两个字典列表:

list1 = [
    {
        "address": "1000",
        "amount": 0
    },
    {
        "address": "2000",
        "amount": 0
    },
    {
        "address": "3000",
        "amount": 0
    },
    {
        "address": "4000",
        "amount": 20
    }
]

list2 = [
    {
        "account": "1000",
        "balance": 100
    },
    {
        "account": "2000",
        "balance": 200
    },
    {
        "account": "3000",
        "balance": 300
    }
]

你的需求是:检查list1里的每个address值是否在list2的account中存在,不存在的话,就把该条目转换成{"account": 原address值, "balance": 原amount值}的格式,添加到list2里。

你之前尝试的代码有问题——它把字典里所有值都塞进集合了,这样会把amount和balance的数值也混进去,没法精准匹配地址/账号。下面是正确的实现思路和代码:

正确实现步骤

  1. 先把list2中所有已有的account值提取出来,存到一个集合里(集合的查找速度比列表快很多)
  2. 遍历list1的每个条目,取出address值,判断是否在集合里
  3. 如果不在,就构造新的字典,转换键名后添加到list2中

完整代码

# 提取list2中已有的account值,存入集合
existing_accounts = {item["account"] for item in list2}

# 遍历list1,处理缺失的条目
for item in list1:
    addr = item["address"]
    if addr not in existing_accounts:
        # 构造新字典并添加到list2
        list2.append({
            "account": addr,
            "balance": item["amount"]
        })

# 打印处理后的list2看看结果
for item in list2:
    print(item)

运行结果

执行后list2会变成:

[
    {"account": "1000", "balance": 100},
    {"account": "2000", "balance": 200},
    {"account": "3000", "balance": 300},
    {"account": "4000", "balance": 20}
]

内容的提问来源于stack exchange,提问作者sethpow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 12:24:59