In question Nested defaultdict of defaultdict is described how to create a nested dictionary. This works so far until I want to increment a non-existing key. See the following example:
#!/usr/bin/python3
from collections import defaultdict
mydict = defaultdict(lambda: 0)
print("mydict['a'] =", mydict['a'])
mydict['b'] = 2
print("mydict['b'] =", mydict['b'])
mydict['c'] += 4
print("mydict['c'] =", mydict['c'])
def rec_dd():
return defaultdict(rec_dd)
x = rec_dd()
x['a']['b']['c']['d'] = 2
print("x['a']['b']['c']['d'] =", x['a']['b']['c']['d'])
x['a']['b']['c']['e'] += 2
print("x['a']['b']['c']['e'] =", x['a']['b']['c']['e'])
which creates the following output
mydict['a'] = 0
mydict['b'] = 2
mydict['c'] = 4
x['a']['b']['c']['d'] = 2
Traceback (most recent call last):
File "./nested.py", line 19, in <module>
x['a']['b']['c']['e'] += 2
TypeError: unsupported operand type(s) for +=: 'collections.defaultdict' and 'int'
For the defaultdict with just one level it is all right to add a value to a non-existing key (mydict['c'] += 4
), for the nested dictionary this does not work, the line x['a']['b']['c']['e'] += 2
fails. How can I achieve this?