Home > Enterprise >  How to filter a dictionary based on a value from inner dictionary
How to filter a dictionary based on a value from inner dictionary

Time:11-05

do you have an ide how do i filter dict structured like this

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

using filter() based value in dictionary inside dictionary? End result should be that lets say i use filter and i receive

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

Thanks for your time

CodePudding user response:

If your condition is, that "remote" is somewhere inside the inner dict values, you can do it with dictionary comprehension:

>>> {k: v for k, v in dictionary.items() if "remote" in v.values()}
{'val2': {'path2': 'remote'}, 'val3': {'path3': 'remote'}, 'val4': {'test4': 'remote'}}

that is basically the same as:

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'}}
  • Related