python recursive add keys to dict when edit dict -


need change in dictionary

d1['a']['b']['c'] = 1 

but possible what

d1['a']['b'] nonexistent must recursively added

expected results

d1={} {'a':{'b':{'c':'1'}}} d1={'a':{'b':{'c':'0'}}} {'a':{'b':{'c':'1'}}} d1={'f':1,'a':{'h':'1','b':{'d':'1'}}} {'f':1,'a':{'h':1,'b':{'c':'1','d':'1'}}} d1={'f':1,'a':{'b':{'c':'0','d':'1'}}} {'f':1,'a':{'b':{'c':'1','d':'1'}}} d1={'f':1,'j':{'h':'1','b':{'d':'1'}}} {'f':1,'a':{'b':{'c':'1'}},'j':{'h':'1','b':{'d':'1'}}} 

ugly way is

if not 'a' in d1.keys():     d1['a'] = {} if not 'b' in d1['a'].keys():     d1['a']['b'] = {} d1['a']['b']['c'] = 1 

but want pretty recursive solution this, editing existent dict.


Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -