首页 > 解决方案 > 在动态字典中查找所有匹配键=值对的字典

问题描述

如果我有一个如下的 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'
                }
              }
            }
          }
        }

我还没有任何工作代码,因为我不确定从哪里开始。我现在只有起始字典。

标签: python

解决方案


您可以使用递归:

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"
            }
        }
     }
   }
}

推荐阅读