首页 > 解决方案 > 如何根据内部字典中的值过滤字典

问题描述

你知道我如何过滤像这样结构的字典吗

dictionary = {
    'val1': {"path1": "local"},
    'val2': {"path2": "remote"},
    'val3': {"path3": "remote"},
    'val4': {"test4": "remote"},
}

在字典内的字典中使用基于过滤器()的值?最终结果应该是假设我使用过滤器并且我收到

filtered_dictionary = {
    'val2': {"path2": "remote"},
    'val3': {"path3": "remote"},
    'val4': {"test4": "remote"},
}

谢谢你的时间

标签: pythondictionaryfiltering

解决方案


如果您的条件是"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'}}

推荐阅读