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

如何补全Python嵌套字典中缺失的客户兼容性双向映射关系?

补全嵌套字典的反向兼容性关系

给定一个单向存储客户兼容性的嵌套字典(仅记录A到B的关系,不重复存储B到A),需要补全所有反向关系,确保每个客户的条目里都包含所有与之有兼容性关联的客户及对应分值。

示例输入

Custdict = {
    '1': {'2': 1, '3': 0, '4': 3},
    '2': {'3': 1, '4': 2},
    '3': {'4': 0}
}

实现代码

# 遍历原字典的主客户及其关联关系(转成list避免迭代时字典结构变化报错)
for main_cust, relations in list(Custdict.items()):
    for related_cust, score in relations.items():
        # 若关联客户未作为主键存在,先创建空条目
        if related_cust not in Custdict:
            Custdict[related_cust] = {}
        # 仅当反向关系未存在时添加,避免重复操作
        if main_cust not in Custdict[related_cust]:
            Custdict[related_cust][main_cust] = score

处理后结果

运行上述代码后,原字典会被补全为:

{
    '1': {'2': 1, '3': 0, '4': 3},
    '2': {'3': 1, '4': 2, '1': 1},
    '3': {'4': 0, '1': 0, '2': 1},
    '4': {'1': 3, '2': 2, '3': 0}
}

代码说明

  • 使用list(Custdict.items())是为了在遍历过程中,即便字典新增键(比如之前不存在的客户10),也不会触发迭代错误
  • 先检查关联客户是否存在于主字典的键中,不存在则创建空字典条目,保证后续可以添加反向关系
  • 增加反向关系存在性检查,避免重复赋值,提升效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:15:40