I want set the keys and values in the dictionary. Here is an example of what I do.
class NestedDict(dict):
def __getitem__(self, key):
if key in self: return self.get(key)
return self.setdefault(key, NestedDict())
>>> c = NestedDict()
>>> c
{}
>>> c['a']['b'] = 'test'
>>> c['a']['c'] = 2
>>> c
{'a': {'c': 2, 'b': 'test'}}
>>> c['a']['c'] += 1
>>> c
{'a': {'c': 3, 'b': 'test'}}
>>> c['a']['d'] += 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +=: 'NestedDict' and 'int'
Any ideas how to solve this problem? I want be able to use += and -=. Of course if value doesn't exist then += 1 is these same as = 1. Maybe there's a better solution?
Thanks.