This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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