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

如何用Python筛选dict_1符合条件的键并统计对应dict_2数值总和?

Python实现字典匹配与求和需求

给定字典

dict_1 = {'mother': ['mother', 'mom', 'mum', 'mommy', 'mummy', 'mamma', 'momma', 'ma', 'mamma'], 
           'boy': ['boy', 'guy', 'dude', 'lad', 'son', 'schoolboy', 'young man'], 
           'girl': ['girl', 'daughter', 'lass', 'schoolgirl', 'young lady'],
           'kitchen': ['kitchen'], 
           'exterior': ['exterior', 'outside', 'outdoor', 'outdoors'],
           'car': ['car', 'vehicule', 'automobile'],
           'water': ['water']
          }

dict_2 = {'basket': 2,
          'car' : 8,
          'juice': 1,
          'window': 6,
          'outside': 2,
          'oudoor': 4,
          'road': 1,
          'mom': 5,
          'mother': 2,
          'song': 1,
          'vehicule': 1,
          'fruits': 6
         }

需求说明

  1. 找出dict_1中所有符合条件的键:该键对应的列表里至少有一个元素是dict_2中值大于1的键
  2. 对符合条件的键,统计其列表中所有满足「存在于dict_2且对应值>1」的元素的数值之和
  3. 最终生成以dict_1符合条件的键为键、统计总和为值的新字典

实现代码

方式一:分步遍历(可读性强)

dict_final = {}
# 遍历dict_1的每个类别及其同义词列表
for category, synonyms in dict_1.items():
    total = 0
    has_valid_item = False
    # 检查每个同义词
    for word in synonyms:
        # 判断是否在dict_2中且值大于1
        if word in dict_2 and dict_2[word] > 1:
            total += dict_2[word]
            has_valid_item = True
    # 只有存在有效元素时才加入结果字典
    if has_valid_item:
        dict_final[category] = total

print(dict_final)
# 输出: {'mother': 7, 'exterior': 2, 'car': 8}
# 注:dict_2中'oudoor'为拼写错误,与dict_1的'outdoor'不匹配,故exterior仅统计outside的2

方式二:字典推导式(简洁高效)

dict_final = {
    category: sum(dict_2[word] for word in synonyms if word in dict_2 and dict_2[word] > 1)
    for category, synonyms in dict_1.items()
    if any(word in dict_2 and dict_2[word] > 1 for word in synonyms)
}

print(dict_final)

逻辑说明

  • any()函数:快速判断当前类别是否存在至少一个符合条件的元素,避免无效统计
  • sum()生成器表达式:遍历同义词列表,仅累加符合条件的元素对应的数值
  • 字典推导式:将遍历、判断、统计逻辑整合为一行代码,兼顾简洁性与可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 10:15:40