Let's say I am given a nested dicionary my_dict
and another nested dict update
: a sequence of keys (valid in my_dict
) with a value to be assigned to the leaf at this sequence. For example,
my_dict = {
'city': 'NYC',
'person1': {'age': 25, 'name': 'Anna'},
'person2': {'age': 30, 'name': 'Bob'}
}
update0 = {'city': 'London'}
update1 = {'person1': {'age': 24}}
update2 = {'person2': {'age': 31}}
I need a function UpdateDict
such that UpdateDict(my_dict, update1)
will return
{
'city': 'NYC',
'person1': {'age': 24, 'name': 'Anna'},
'person2': {'age': 30, 'name': 'Bob'}
}
and UpdateDict(my_dict, update0)
will return
{
'city': 'London',
'person1': {'age': 25, 'name': 'Anna'},
'person2': {'age': 30, 'name': 'Bob'}
}
In c++ I would have used explicit pointers/references to subdicts, but in python I'm not sure what to do, given that I don't know in advance the depth of the second argument (update
one).
EDIT: if I try {**my_dict, **update1}
or my_dict.update(update1)
I get
{
'city': 'NYC',
'person1': {'age': 24},
'person2': {'age': 30, 'name': 'Bob'}
}
which is not desired: it does not change the value at a particular leaf only, but instead removes all the keys at the same level.
EDIT2: if someone needs this, I've solved it as follows
def UpdateDict(original, param):
for key in param.keys():
if type(param[key]) == dict:
UpdateDict(original[key], param[key])
else:
original[key] = param[key]