python-3.x - 有没有一种快速的方法来检查嵌套对象属性是否等于一个值?
问题描述
我想快速检查字典中的某个属性(或嵌套属性)是否等于“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!'
}
}
}
有什么好的方法来处理这个吗?为此,字典可能非常大,因此循环到每个字典并检查在计算上是非常昂贵的。
解决方案
您可能从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'))
推荐阅读
- javascript - 此条件在检查假值时返回布尔值,但在检查真值时返回字符串。我怎样才能让它工作?
- mongodb - 如何根据配置创建 Spark 连接 str?
- python - 执行 Pyspark 作业时顶点失败
- android - onMessageReceived(RemoteMessage remoteMessage) 应用程序在后台或被杀死时不调用
- python - 从字符串开始提取字符串
- powershell - PowerShell:我正在尝试通过 PS 脚本在我的桌面上生成快捷方式,但出现以下错误
- angular - 在 swiper appendSlide() 中渲染角度组件
- windows - 我如何简单地从我的批处理文件中终止一个进程?
- python - 在我尝试安装 pip install -r requirements.txt 文件后,Docker 构建出现错误
- android - 在模块 classes.jar (com.stripe:stripe-3ds2-android:4.0.5) 和 classes.jar (opentok-android-sdk-2.18.0.aar) 中发现重复的类 aaaaaa