My goal is to, given a python dict which I call datainit
, create a recursive collections.defaultdict
which I call data
, such as data
is initialised with datainit
, and data
can be extended with any path of missing keys,
as illustrated below
from collections import *
datainit={'number':1}
data =something_with(defaultdict(), datainit)
data['A']['B']['C']=3
#At this stage, I want:
#data['A']['B']['C'] ==3
#data['number'] == 1
#and nothing else.
The normal way to do that starting with an empty dict is, for instance:
nested_dict = lambda: defaultdict(nested_dict)
data = nested_dict()
Trying:
nested_dict = lambda: defaultdict(nested_dict, datainit)
data = nested_dict()
Will logically result in my datainit being duplicated for each missing key:
>>> datainit={'number':1}
>>> nested_dict = lambda: defaultdict(nested_dict, datainit)
>>> data=nested_dict()
>>> data
defaultdict(<function <lambda> at 0x7f58e5323758>, {'number': 1})
>>> data['A']['B']['C']=2
>>> data
defaultdict(<function <lambda> at 0x7f58e5323758>, {'A': defaultdict(<function <lambda> at 0x7f58e5323758>, {'B': defaultdict(<function <lambda> at 0x7f58e5323758>, {'C': 2, 'number': 1}), 'number': 1}),
'number': 1})
All this makes sense, but how do I do to just start with an initial dict and then just use an empty dict for each missing keys?
What should be my something_with(defaultdict(), datainit)
.
Probably obvious, but I cannot see it!