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

如何基于另一字典的匹配项向现有字典的内部列表添加值

解决方法

核心思路

先将dictionary2预处理为「用户 -> {匹配ID: 待追加内容}」的二级映射结构,避免匹配时出现值对应错误,后续遍历dictionary1时可直接通过ID快速查询到需要追加的内容。

实现代码

# 第一步:构建匹配查找表
lookup = {}
for user, items in dictionary2.items():
    lookup[user] = {}
    for item in items:
        match_id = item[0]
        append_val = item[1]
        lookup[user][match_id] = append_val

# 第二步:遍历dictionary1完成合并
for user, records in dictionary1.items():
    if user not in lookup:
        continue
    match_map = lookup[user]
    for record in records:
        current_id = record[0]
        if current_id in match_map:
            record.append(match_map[current_id])

# 输出验证结果
print(dictionary1)

原代码问题说明

你之前的实现把所有匹配ID和待追加内容都存入了同一个一维列表inter1,没有建立「用户+匹配ID」和对应待追加值的绑定关系,所以匹配成功后无法取出对应单个值,只能把整个列表追加到末尾,导致结果不符合要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 15:36:03