0

I am trying to return True if a key already exists in the big dictinary or any subdictionary that is a part of this dict and False if it does not: here is my code:

def find_key(key, dicto):
    for k, v in dicto.items():
        if k == key:
            return v
        elif isinstance(v, dict):
            for result in find_key(key, v):
                return result

where am I going wrong ? here what i want :

data = {
    "spam": {
        "egg": {
            "erwan": "Well..",
            "a": "ezeaea",
            "sausages": "Spam egg sausages and spam",
            "jih": "je sais pas "
        },
        "oui": ''
    }
}
find_key("oui", data) return True
find_key("jih", data) return True  
find_key("oezea", data) return False 
MelDev
  • 275
  • 1
  • 6
  • 18
  • No already tried and didn't work i want to return True if it exist and False otherwise – MelDev May 28 '18 at 15:24
  • look here: https://stackoverflow.com/questions/43491287/elegant-way-to-check-if-a-nested-key-exists-in-a-python-dict – Lior Alon May 28 '18 at 15:24
  • not the same case, i want to check if a key exist not a list of key in order – MelDev May 28 '18 at 15:25
  • How about you check the list at the end and if it's empty return False, otherwise True. Just because the duplicate doesn't give you an exact solution does not make it not useful. You need to put forth some effort. – user3483203 May 28 '18 at 15:25
  • yes how that possible, this what i m looking for – MelDev May 28 '18 at 15:27
  • You can use Recursion maybe. I cant comment because this is blocked, but take each element in your original dic, and run the same function on it, and then recursively check the dics in them etc, return true if one returns true. – Lior Alon May 28 '18 at 15:28
  • Something like this: def keys_exists(element, key): if type(element) is not dict: return false if dict in element.keys: return true rec = Map(lamda x: keys_exists(x), element.values) return True in rec – Lior Alon May 28 '18 at 15:32

0 Answers0