首页 > 解决方案 > 如何根据列表中的键和值弹出或过滤嵌套字典?

问题描述

我想根据列表中的值创建一个子集字典,但不确定最好的方法。

我有一本这样设置的字典:

animal_dict = {'dog': {'color': {'white': 10,
                                 'yellow': 20,
                                 'brown': 30},
                      'attributes': {'legs': 4, 
                                     'teeth': 42}},
               'cat': {'color': {'white': 8,
                                   'calico': 10,
                                   'yellow': 12},
                      'attributes': {'legs': 4, 
                                     'teeth': 30}}
              }

..我有一些我想保留的项目的关键值:

keep_animal = ['dog']
keep_color = ['white', 'yellow']

我的预期结果如下所示:

{'dog': {'color': {'white': 10,
                   'yellow': 20},
         'attributes': {'legs': 4, 
                        'teeth': 42}}}

提前致谢!

标签: pythondictionary

解决方案


为什么不做反向而不是让你放弃任何你不需要的父键。

unwanted_parent_keys = ['cat', 'brown']
def keep_key(input_dict, drop_keys):
    new_dict = {}
    for k, v in input_dict.items():
        if k in drop_keys:
            continue
        if isinstance(v, dict):
            new_dict[k] = keep_key(v, drop_keys)
        else:
            new_dict[k] = v
    return new_dict

new_animal_dict = keep_key(animal_dict, unwanted_parent_keys)

推荐阅读