python - 在动态字典中查找所有匹配键=值对的字典
问题描述
如果我有一个如下的 python 字典:
conf = {
'memory': {
'alarm': {
'active': 'yes',
'pagefile_error': {
'active':'no'
}
}
},
'disk': {
'alarm':{
'active':'yes',
'fixed':{
'#dev':{
'active':'yes',
'something':'else'
}
}
}
},
'cpu': {
'alarm': {
'active':'no',
'highcpu': {
'active':'yes'
}
}
}
}
如何仅过滤以 'active':'yes' 结尾的路径而不显示任何其他信息。
此外,对于显示为活动的父项:不,我想忽略之后的任何内容。
conf = {
'memory': {
'alarm': {
'active': 'yes'
}
},
'disk' : {
'alarm':{
'active':'yes',
'fixed': {
'#dev': {
'active':'yes'
}
}
}
}
}
我还没有任何工作代码,因为我不确定从哪里开始。我现在只有起始字典。
解决方案
您可以使用递归:
def active(d):
_r, _flag = [], False
for a, b in d.items():
if a == 'active' and not _flag:
_r.append(b == 'yes')
_flag = True
if not _flag and isinstance(b, dict):
_r.append(active(b))
return all(_r)
def build(d, flag = False):
return {a:b if not isinstance(b, dict) else build(b, 'active' in b)
for a, b in d.items() if ((not isinstance(b, dict) and not flag) or a == 'active') or (isinstance(b, dict) and active(b))}
import json
print(json.dumps(build(conf), indent=4))
输出:
{
"memory": {
"alarm": {
"active": "yes"
}
},
"disk": {
"alarm": {
"active": "yes",
"fixed": {
"#dev": {
"active": "yes"
}
}
}
}
}
推荐阅读
- c# - 未找到 UWP 资源
- node.js - 在 DynamoDB 中,您可以 UpdateItem 忽略未定义的值吗?
- javascript - jQuery幻灯片出现和消失在同一个按钮点击
- python - Python 的 os.fstat 在每个平台上都可用吗?
- python - 输出显示类似 Series([], ),如何解决这个问题?
- python - 如何使用 QWebEngineView 刷新一个 QApplication 与一个计划周期
- python - 具有所有相关对象的重复模型实例
- javascript - 如何以更好的方式编写它,例如 lodash
- jmeter - Jmeter 最大值随时间递减
- hash - 局部敏感散列可以应用于动态维数据点吗?