python - 如何根据内部字典中的值过滤字典
问题描述
你知道我如何过滤像这样结构的字典吗
dictionary = {
'val1': {"path1": "local"},
'val2': {"path2": "remote"},
'val3': {"path3": "remote"},
'val4': {"test4": "remote"},
}
在字典内的字典中使用基于过滤器()的值?最终结果应该是假设我使用过滤器并且我收到
filtered_dictionary = {
'val2': {"path2": "remote"},
'val3': {"path3": "remote"},
'val4': {"test4": "remote"},
}
谢谢你的时间
解决方案
如果您的条件是"remote"
内部dict
值内部的某个位置,则可以使用字典理解来做到这一点:
>>> {k: v for k, v in dictionary.items() if "remote" in v.values()}
{'val2': {'path2': 'remote'}, 'val3': {'path3': 'remote'}, 'val4': {'test4': 'remote'}}
这基本上与以下内容相同:
out = {}
for k, v in dictionary.items():
if "remote" in v.values():
out[k] = v
>>> out
{'val2': {'path2': 'remote'}, 'val3': {'path3': 'remote'}, 'val4': {'test4': 'remote'}}
推荐阅读
- java - 通过uri将图像设置为imageView时出现OOM
- python - 为什么 django-channels 不连接到安全的 Websockets wss?
- odoo-14 - Odoo 在 res.partner 添加字段并显示在 account_aged_partner_balance
- wordpress - Woocommerce 添加第二个结帐页面进行测试
- wordpress - WP_Query 具有分类的自定义帖子类型不起作用
- r - 将具有 3 列的数据框转换为加权邻接矩阵
- javascript - 可以在 Electron 中过滤 URL 吗?
- r - 为什么 uniroot() 给出错误的结果?
- wordpress - Wordpress,所有插件更新,“更新失败:访问被拒绝。”
- javascript - 无限循环等待变量值改变,并在 mongo shell 中每 30 秒检查一次