Below is a sample code:
from collections import defaultdict
normal_dict = {
"test": {
"test1": 1,
"test2": 2,
"test3": {
"test3_1": 1
}
}
}
default_dict = defaultdict(lambda: defaultdict(dict), normal_dict)
default_dict['test']['test4']['test4_1'] = 1 # Doesn't work
print(default_dict)
I get this error
Traceback (most recent call last):
File "<string>", line 17, in <module>
KeyError: 'test4'
It seems like the previously non-existent key 'test4'
is not being automatically added when I use the line default_dict['test']['test4']['test4_1']
, for some reason. Theoretically, defaultdict should create the key test4
with another defaultdict as its default value.