0

I want to quickly check if one of the attributes (or nested attributes) in a dictionary is equal to "cat".

The dictionary could look like this:

my_dict = {
  'dog': 'woof',
  'child':{
      'duck': 'quack'.
      'grandchild': {
         'best': 'cat'
      }
    }
}

Is there a quick way to check if 'cat" is on of the attribute values. I could do something like:

if 'cat' in json.dumps(my_dict):

But that doesn't solve this edge case:

{
  'dog': 'woof',
  'child':{
      'duck': 'quack'.
      'grandchild': {
         'best', 'This is a cat in a sentence, should be found!'
      }
    }
}

Any good way to handle this? For this, the dictionaries could be quite large, so looping into each and checking is very computationally expensive.

superdee
  • 637
  • 10
  • 23

1 Answers1

0

You probably found an answer to this from the comment Devesh Kumar Singh made with the link but in case you had trouble with those answers or if someone else comes to look at your question here is an answer:

# This will be our test nested dictionary.
d = {
  'dog': 'woof',
  'child':{
      'duck': 'quack',
      'grandchild': {
         'best': 'This is a cat in a sentence, should be found!'
      }
    }
}

def recursive_search(dic, search_key):
    """
    Takes a dictionary and looks for the desired key
    at both the top level and for all nested dicts.
    """
    # If the key is in the current dict
    # at top level then return true
    if search_key in dic:
        return True
    # Else we need to make sure it isn't in a nested dict
    # For each key value pair in our current dict
    for cur_key, val in dic.items():
        # If the value for this cur_key is a dict
        if isinstance(val, dict):
            # Check if the nested dic contains our key
            if recursive_search(val, search_key):
                # If it does return true
                return True
            # If it doesn't continue on to the next item in our dict
    # search_key not found.
    return False

print(recursive_search(d, 'best'))