Skip to content

Instantly share code, notes, and snippets.

@IndhumathyChelliah
Created Jul 9, 2020
Embed
What would you like to do?
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