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

如何检查值是否存在于Python嵌套字典中?代码问题求助

嵌套字典中检查特定值是否存在的解决方案

问题重现

你有如下嵌套字典,需要实现检查特定嵌套值是否存在的功能,但当前函数无法正常工作:

dictionary = {
    "UID1" : {
        "es" : {
            "lemma" : "caminar",
            "conjugations" : {
                "present_simple" : {
                    "1ps" : "camino",
                    "2ps" : "caminas",
                    "3ps" : "camina",
                    "1pp" : "caminamos",
                    "2pp" : "camináis",
                    "3pp" : "caminan"
                }
            }
        }
    },
    "UID2" : {
        "es" : {
            "lemma" : "cocinar",
            "conjugations" : {
                "present_simple" : {
                    "1ps" : "cocino",
                    "2ps" : "cocinas",
                    "3ps" : "cocina",
                    "1pp" : "cocinamos",
                    "2pp" : "cocináis",
                    "3pp" : "cocinan"
                }
            }
        }
    }
}

def word_check(word):
    if any (word) in dictionary.values():
        print("Yes")
    else:
        print("No")

word_check("camino")

原函数逻辑错误:any(word)会把字符串拆成单个字符判断,且dictionary.values()仅能获取第一层字典,无法深入嵌套结构。

可行解决方案

方法1:递归遍历所有嵌套值

递归是处理任意嵌套结构的通用方式,遍历所有键值对,遇到字典则继续递归,遇到值则检查是否匹配:

def word_check(word):
    def search_nested(obj):
        if isinstance(obj, dict):
            for value in obj.values():
                if search_nested(value):
                    return True
        else:
            return obj == word
    print("Yes" if search_nested(dictionary) else "No")

word_check("camino")  # 输出 Yes
word_check("comer")   # 输出 No

方法2:迭代式遍历(避免递归深度问题)

如果嵌套层级极深,递归可能触发栈溢出,用迭代+栈的方式更安全:

def word_check(word):
    stack = list(dictionary.values())
    while stack:
        current = stack.pop()
        if isinstance(current, dict):
            stack.extend(current.values())
        else:
            if current == word:
                print("Yes")
                return
    print("No")

word_check("camino")  # 输出 Yes

方法3:针对固定结构的优化(更Pythonic)

如果你的字典结构固定(UID -> es -> lemma/conjugations),可以针对性遍历,效率更高:

def word_check(word):
    for uid_data in dictionary.values():
        es_data = uid_data["es"]
        # 检查词根和所有变位形式
        if es_data["lemma"] == word:
            print("Yes")
            return
        for conj_group in es_data["conjugations"].values():
            if word in conj_group.values():
                print("Yes")
                return
    print("No")

word_check("camino")  # 输出 Yes
word_check("caminar") # 输出 Yes

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 15:46:09