Skip to content

Instantly share code, notes, and snippets.

@IndhumathyChelliah
Created July 9, 2020 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IndhumathyChelliah/54528a0a43ccc2780c720055358dd686 to your computer and use it in GitHub Desktop.
Save IndhumathyChelliah/54528a0a43ccc2780c720055358dd686 to your computer and use it in GitHub Desktop.
from collections import ChainMap
class DeepChainMap(ChainMap):
def __setitem__(self, key, value):
for mapping in self.maps:
if key in mapping:
mapping[key] = value
return
self.maps[0][key] = value
def __delitem__(self, key):
for mapping in self.maps:
if key in mapping:
del mapping[key]
return
raise KeyError(key)
d = DeepChainMap({'a': 1}, {'b': 2}, {'c': 3})
print (d)#Output:DeepChainMap({'a': 1}, {'b': 2}, {'c': 3})
#Updating existing key two levels down
d['c'] = 99
print (d)#Output:DeepChainMap({'a': 1}, {'b': 2}, {'c': 99})
#Adding new keys to first mapping
d['e'] = 5
print (d)#Output:DeepChainMap({'a': 1, 'e': 5}, {'b': 2}, {'c': 99})
#Deleting an existing key in second mapping(one level down)
del d['b']
print (d)#Output:DeepChainMap({'a': 1, 'e': 5}, {}, {'c': 99})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment