Skip to content

Instantly share code, notes, and snippets.

@gauravvjn
Created April 19, 2018 10:31
Show Gist options
  • Save gauravvjn/6db10148542b64e69d8a1a562986576f to your computer and use it in GitHub Desktop.
Save gauravvjn/6db10148542b64e69d8a1a562986576f to your computer and use it in GitHub Desktop.
Source nested Dictionary filtering based on mapping dict whose all keys are present in Source dictionary in the same structure
def filter_dict(src_dict, mapping_dict):
for k, v in list(src_dict.items()):
if k not in mapping_dict:
del src_dict[k]
elif isinstance(v, dict) and isinstance(mapping_dict[k], dict):
src_dict[k] = filter_dict(v, mapping_dict[k])
return src_dict
# ------------------------ TEST ------------------------
source_dict = {
'a': 1,
'b': {
'd': {
'f': 4,
'g': 5
},
'e': 3
},
'c': 2,
'x': 'hello'
}
mapping_dict = {
'a': None,
'b': {
'd': {
'g': None
},
},
'x': None
}
filter_dict(source_dict, mapping_dict)
# {'a': 1, 'x': 'hello', 'b': {'d': {'g': 5}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment