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

如何遍历含嵌套字典的字典并将每个嵌套字典与输入字典进行匹配?

如何遍历含嵌套字典的字典并将每个嵌套字典与输入字典进行匹配?

嘿,我来帮你把这个问题彻底解决掉!你已经找到了关键的字典匹配逻辑,现在只需要把它和遍历嵌套字典的步骤结合起来,就能得到想要的结果啦。

先回顾下你的需求:我们有一个input_dict,还有一个包含多个子字典的nested_dict,要找出所有外层键,使得对应的子字典里的每一组键值对都能在input_dict里找到完全匹配的项(input_dict里多出来的键值对不用管)。

先把你的示例数据放出来:

input_dict = {1:23, 2:34, 3:45, 4:56}
nested_dict = {'one':{1:23}, 'two':{1:23, 2:34}, 'three':{1:23, 2:34, 5:67}}

完整实现思路

核心就是遍历nested_dict的每一个外层键和对应的子字典,用你找到的all()逻辑去验证匹配性,把符合条件的外层键收集起来就行。

直接上完整代码:

input_dict = {1:23, 2:34, 3:45, 4:56}
nested_dict = {'one':{1:23}, 'two':{1:23, 2:34}, 'three':{1:23, 2:34, 5:67}}

result = []
# 遍历嵌套字典的外层键和子字典
for outer_key, sub_dict in nested_dict.items():
    # 检查子字典的所有键值对是否都在input_dict中匹配
    if all(key in input_dict and input_dict[key] == sub_dict[key] for key in sub_dict):
        result.append(outer_key)

print(result)  # 输出: ['one', 'two']

代码解释

  • 用nested_dict.items()可以同时拿到外层的标识键(比如'one')和对应的子字典;
  • 你写的all()表达式是关键:它会逐个检查子字典里的每个键,先确认这个键存在于input_dict中,再确认两者的对应值完全相等。只有当子字典的所有键值对都满足这个条件时,才会返回True;
  • 只要匹配成功,就把外层键加入结果列表,最后得到的就是符合要求的键集合。

小优化:用列表推导式简化代码

如果想要更简洁的写法,可以把匹配逻辑封装成一个小函数,再用列表推导式完成收集:

def is_subdict_matched(sub_dict, target_dict):
    return all(key in target_dict and target_dict[key] == sub_dict[key] for key in sub_dict)

# 一行完成筛选
result = [outer_key for outer_key, sub_dict in nested_dict.items() if is_subdict_matched(sub_dict, input_dict)]
print(result)  # 同样输出: ['one', 'two']

这样代码的可读性会更好,后续如果要修改匹配规则,直接调整函数就行。

备注:内容来源于stack exchange,提问作者E Farley

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 11:19:38