有没有一种快速的方法来检查嵌套对象的属性是否等于值?

时间:2019-04-11 02:25:40

标签: python-3.x dictionary

我想快速检查一下字典中的一个属性(或嵌套属性)是否等于“ cat”。

字典可能看起来像这样:

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

有没有一种快速的方法来检查'cat'是否位于属性值上。我可以执行以下操作:

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

但这不能解决这种极端情况:

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

有什么好办法解决这个问题吗?为此,字典可能很大,因此循环进入每个字典并进行检查在计算上非常昂贵。

1 个答案:

答案 0 :(得分:0)

您可能从链接中的 Devesh Kumar Singh 评论中找到了答案,但是如果您对这些答案有疑问,或者如果有人来看看您的问题,这里就是答案:

# 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'))