1

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]
SBF
  • 345
  • 1
  • 2
  • 14
  • I'm not sure why `my_dict.update(update)` wouldn't work. – mkrieger1 Aug 24 '22 at 21:51
  • @mkrieger1: because it removes other keys at that level – SBF Aug 24 '22 at 22:01
  • I see. Then you probably need a recursive solution. – mkrieger1 Aug 24 '22 at 22:04
  • @mkrieger1 I probably do, but I don't see how to avoid changing the value on a copy of a subdict, and instead change it in the original dict. I also don't get why this question was immediately closed, even though the suggested link does not answer it – SBF Aug 24 '22 at 22:05
  • Unless you explicitly create a copy, you should normally operate on references already. – mkrieger1 Aug 24 '22 at 22:07
  • @mkrieger1 indeed, that worked – SBF Aug 25 '22 at 09:22
  • 1
    @Barmar the duplicate should be https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth – mkrieger1 Aug 25 '22 at 09:45
  • @mkrieger1 that's better, thanks – SBF Aug 25 '22 at 11:50
  • @mkrieger1 Yeah, that question is directly on point, although there are some answers to my duplicate that show how to do it recursively. – Barmar Aug 25 '22 at 15:26

0 Answers0