pythondictionary

Trying to find if value exists in nested dictionary


I have the following nested dictionary, but I can't figure out how to get a particular nested value:

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")

But this doesn't work.

I considered a for loop but I couldn't figure out how to get it to go through the nested keys in an agnostic way. Also checked recursive loops but can't figure those out either. I feel like I'm almost there but can't quite put it together...

Something like:

dictionary.values() = primary_key
primary_key.values() = layer_one
layer_one.values() = layer_two
etc.

But that doesn't seem terribly pythonic...


Solution

  • def value_exists(nested_dict, target_value):
        for key, value in nested_dict.items():
            if isinstance(value, dict):
                if value_exists(value, target_value):
                    return True
            elif value == target_value:
                return True
        return False
    
    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"
                    }
                }
            }
        }
    }
    
    print(value_exists(dictionary, "camino"))  # True
    print(value_exists(dictionary, "correr"))  # False