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

如何检索嵌套字典中的指定键值对(如detected=True的条目)

检索嵌套字典中特定条件的条目

首先给出你的示例数据字典:

result = {
    'CMC Threat Intelligence': {'detected': False, 'result': 'clean site'},
    'Snort IP sample list': {'detected': True, 'result': 'clean site'},
    '0xSI_f33d': {'detected': False, 'result': 'unrated site'}
}

你之前的循环只遍历了外层字典的键,要访问内层字典的内容,得用items()方法同时获取外层的名称(键)和对应的内层结果字典(值),以下是两种需求的实现方案:

场景1:找出所有detected值为True的条目

# 收集符合条件的条目
detected_true_entries = []
for tool_name, result_dict in result.items():
    if result_dict['detected'] is True:
        detected_true_entries.append((tool_name, result_dict))

# 输出结果
for entry in detected_true_entries:
    print(f"工具名称: {entry[0]}, 检测详情: {entry[1]}")

逻辑说明:遍历外层字典的键值对,判断内层字典的detected字段是否为True,符合条件的条目会被存入列表,之后可按需输出或进一步处理。

场景2:找出所有result值为“clean site”的内容

如果只需要快速打印结果,可直接在循环中判断输出:

for tool_name, result_dict in result.items():
    if result_dict['result'] == 'clean site':
        print(f"{tool_name}: {result_dict['result']}")

如果需要保存结果后续使用,同样可以存入列表:

clean_site_entries = []
for tool_name, result_dict in result.items():
    if result_dict['result'] == 'clean site':
        clean_site_entries.append((tool_name, result_dict))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:20:42