首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在动态字典中查找与key=value对匹配的所有字典

在动态字典中查找与key=value对匹配的所有字典
EN

Stack Overflow用户
提问于 2019-06-05 15:12:48
回答 3查看 61关注 0票数 0

如果我有一个python字典,如下所示:

代码语言:javascript
复制
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'
             }
           }
         }
       }

如何只过滤以“活动”结尾的路径:“是的”,而不显示任何其他信息。

此外,对于显示为活动的父项目:不,我想忽略那些之后的任何事情。

代码语言:javascript
复制
conf = {
         'memory': {
           'alarm': {
             'active': 'yes'
           }
         },
         'disk' : {
           'alarm':{
             'active':'yes',
             'fixed': {
               '#dev': {
                 'active':'yes'
                }
              }
            }
          }
        }

我还没有这方面的任何工作代码,因为我不知道从哪里开始。我现在只有一本字典。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-06-05 15:58:09

使用递归:

代码语言:javascript
复制
def keep_active_only(my_dict):
    result_dict = {}

    for key, value in my_dict.items():

        # If there is embedded dict
        if isinstance(value, dict):
            # Compute the embedded dict using recursion
            result_subdict = keep_active_only(value)

            # Keeping result only if not empty
            if result_subdict:
                result_dict[key] = result_subdict

        # Keep active key if value is yes
        elif key == "active" and value == "yes":
            result_dict[key] = value

        # Returns empty dict if active is no
        elif key == "active" and value == "no":
            return {}

    return result_dict

产出:

代码语言:javascript
复制
>>> keep_active_only(conf)
{
  'disk': {
    'alarm': {
      'active': 'yes',
      'fixed': {
        '#dev': {
          'active': 'yes'
        }
      }
    }
  },
  'memory': {
    'alarm': {
      'active': 'yes'
    }
  }
}
票数 1
EN

Stack Overflow用户

发布于 2019-06-05 15:52:47

您可以使用递归:

代码语言:javascript
复制
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))}
代码语言:javascript
复制
import json
print(json.dumps(build(conf), indent=4))

输出:

代码语言:javascript
复制
{
  "memory": {
    "alarm": {
        "active": "yes"
    }
},
 "disk": {
    "alarm": {
        "active": "yes",
        "fixed": {
            "#dev": {
                "active": "yes"
            }
        }
     }
   }
}
票数 1
EN

Stack Overflow用户

发布于 2019-06-05 15:29:12

不确定是否正确理解,但这里有一个函数,它丢弃dict中的所有数据,这些数据不会带您到特定的键和值:

代码语言:javascript
复制
def filter_dict(d, key, value):
    new_dict = {}
    for d_key, d_value in d.items():
        if d_key == key and d_value == value:
            new_dict[d_key] = d_value
        elif isinstance(d_value, dict):
            child = filter_dict(d_value, key, value)
            if child:
                new_dict[d_key] = child
    return new_dict

下面是如何在您的示例中使用它:

代码语言:javascript
复制
from pprint import pprint

conf = {
    'memory': {
        'alarm': {
            'active': 'yes',
            'pagefile_error': {
                'active':'no'
            }
        }
    },
    'disk': {
        'alarm': {
            'active': 'yes',
            'fixed': {
                '#dev': {
                    'active': 'yes',
                    'something': 'else'
                }
            }
        }
    }
}
pprint(filter_dict(conf, 'active', 'yes'))
# {'disk': {'alarm': {'active': 'yes', 'fixed': {'#dev': {'active': 'yes'}}}},
#  'memory': {'alarm': {'active': 'yes'}}}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56463334

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档