I have a dict subclass whose job is to dynamically add nested dict key if it not exists and do list append if append is called:
class PowerDict(dict):
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
def append(self,item):
if type(self) != list:
self = list()
self.append(item)
so
a = PowerDict()
a['1']['2'] = 3
produce output:
a = {'1': {'2': 3}}
However, sometime i need to do something like this:
b = PowerDict()
b['1']['2'].append(3)
b['1']['2'].append(4)
should produce output:
b = {'1': {'2': [3, 4]}}
but above code produce output:
{'1': {'2': {}}}
What i am missing?
class PowerDict(dict):
# http://stackoverflow.com/a/3405143/190597 (gnibbler)
def __init__(self, parent = None, key = None):
self.parent = parent
self.key = key
def __missing__(self, key):
self[key] = PowerDict(self, key)
return self[key]
def append(self, item):
self.parent[self.key] = [item]
def __setitem__(self, key, val):
dict.__setitem__(self, key, val)
try:
val.parent = self
val.key = key
except AttributeError:
pass
a = PowerDict()
a['1']['2'] = 3
print(a)
b = PowerDict()
b['1']['2'].append(3)
b['1']['2'].append(4)
print(b)
a['1']['2'] = b
a['1']['2'].append(5)
print(a['1']['2'])
yields
{'1': {'2': 3}}
{'1': {'2': [3, 4]}}
[5]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With