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

如何在嵌套字典中搜索到"Iron Man"子串后返回key_three父字典?

嘿,我来帮你解决这个问题!针对你给出的嵌套字典结构,我们可以写一个递归遍历的函数,精准定位到包含目标子串的key_three对应的值。

解决方案

1. 先明确输入数据

先把你的原始嵌套字典列表定义清楚:

somedict = [
    {
        "anyKey": 1,
        "key_two": 2,
        "key_three": {
            "key_three_one": "spiderman",
            "key_three_two": "superman",
            "key_three_three": {
                "from_asguard": "is not Iron Man:batman"
            }
        }
    }
]

2. 核心实现函数

我们可以通过递归遍历+目标匹配的方式,先定位到所有key_three的位置,再检查该字典下的所有嵌套值是否包含目标子串,一旦匹配成功就返回整个key_three对应的字典:

def find_target_key_three(data, target_substring):
    # 遍历列表中的每个字典项
    for item in data:
        for key, value in item.items():
            if key == "key_three":
                # 递归检查当前key_three字典下的所有嵌套内容
                def check_nested(nested_dict):
                    for k, v in nested_dict.items():
                        if isinstance(v, dict):
                            if check_nested(v):
                                return True
                        # 检查字符串中是否包含目标子串
                        elif isinstance(v, str) and target_substring in v:
                            return True
                    return False
                
                # 如果当前key_three包含目标子串,直接返回整个字典
                if check_nested(value):
                    return value
    # 未找到符合条件的内容时返回None
    return None

# 调用函数获取结果
result = find_target_key_three(somedict, "Iron Man")
print(result)

3. 运行结果

执行上述代码后,你会得到符合预期的输出:

{
    'key_three_one': 'spiderman',
    'key_three_two': 'superman',
    'key_three_three': {'from_asguard': 'is not Iron Man:batman'}
}

额外说明

  • 如果你的数据中存在多个key_three项,这个函数会返回第一个匹配成功的结果;如果需要收集所有符合条件的key_three值,可以把返回逻辑改成往列表中追加结果。
  • 递归遍历的方式支持任意深度的嵌套字典,不用担心层级过深的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:00:19