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

如何将嵌套字典SystemDicto3的列表项追加至同结构的SystemDictu4?

解决嵌套字典列表追加的问题

这事儿其实挺 straightforward 的,既然两个字典结构完全一致——都是以系统编号为键、对应邮箱列表为值,那核心思路就是遍历SystemDicto3里的每一组系统编号和邮箱列表,把邮箱追加到SystemDictu4对应的列表里就行。

基础实现代码

先给你最直接的版本,只处理SystemDictu4里已经存在的系统编号,这里要注意用extend()而不是append(),避免把整个列表当成单个元素塞进目标列表里:

# 遍历SystemDicto3的所有键值对
for system_id, new_emails in SystemDicto3.items():
    # 检查目标字典里是否有这个系统编号
    if system_id in SystemDictu4:
        # 把新邮箱列表的元素逐个追加进去
        SystemDictu4[system_id].extend(new_emails)
    else:
        # 可选操作:如果目标字典里没有这个系统编号,你可以选择直接新增,或者跳过
        # 用copy()是为了避免后续修改原字典的列表时影响到目标字典
        SystemDictu4[system_id] = new_emails.copy()

进阶:处理重复邮箱

如果你的需求里需要避免同一个邮箱在列表里重复出现,可以在追加的时候做去重处理,分两种场景给你方案:

  1. 不在乎邮箱顺序的话,用集合去重最省心:
for system_id, new_emails in SystemDicto3.items():
    if system_id in SystemDictu4:
        # 合并现有列表和新列表,转集合去重再转回列表
        unique_emails = list(set(SystemDictu4[system_id] + new_emails))
        SystemDictu4[system_id] = unique_emails
    else:
        # 新系统的邮箱也顺便去重
        SystemDictu4[system_id] = list(set(new_emails))
  1. 需要保持邮箱的原有顺序,同时去重:
for system_id, new_emails in SystemDicto3.items():
    if system_id in SystemDictu4:
        existing_emails = SystemDictu4[system_id]
        # 只添加那些不在现有列表里的邮箱,保留顺序
        filtered_emails = [email for email in new_emails if email not in existing_emails]
        existing_emails.extend(filtered_emails)
    else:
        SystemDictu4[system_id] = new_emails.copy()

补充:关于从DataFrame生成SystemDicto3

顺便提一句,如果你是从dfo3数据帧生成的SystemDicto3,通常是用分组聚合的方式,比如:

# 假设你的DataFrame有system_id和email两列
SystemDicto3 = dfo3.groupby('system_id')['email'].apply(list).to_dict()

这种方式生成的字典完全适配上面的代码,直接用就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 06:56:59