首页 > 解决方案 > 有没有一种快速的方法来检查嵌套对象属性是否等于一个值?

问题描述

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

字典可能如下所示:

my_dict = {
  'dog': 'woof',
  'child':{
      'duck': 'quack'.
      'grandchild': {
         'best': '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!'
      }
    }
}

有什么好的方法来处理这个吗?为此,字典可能非常大,因此循环到每个字典并检查在计算上是非常昂贵的。

标签: python-3.xdictionary

解决方案


您可能从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'))

推荐阅读