python - 如何根据列表中的键和值弹出或过滤嵌套字典?
问题描述
我想根据列表中的值创建一个子集字典,但不确定最好的方法。
我有一本这样设置的字典:
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}}}
提前致谢!
解决方案
为什么不做反向而不是让你放弃任何你不需要的父键。
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)
推荐阅读
- c# - 如何在 C#、.net 中找到 JObject 的必填字段?
- c++ - 带参数的 C++ 宏
- c++ - 报错:使用 StartServiceCtrlDispatcher(entrytable) 时访问冲突
- html - 如何让悬停时出现的文本显示在 div 的中心(水平和垂直)
- java - 从 mongo 集合 collection.find(query) 中检索数据
- rake - db:migrate 看起来它不能加载我的 rake 文件的一部分
- python - 使用 tf.lite.Optimize.DEFAULT 后,并非 DNN 模型中的所有值都被量化
- vue.js - 实时 vuetify 数据表不使用 axios 更新
- google-sheets - 可视化动态更新的数据
- ibm-cloud - 找不到资源组(即使是默认的)