Give 2 Python dictionaries such as
a1 = {'a': 2, 'b': 3, 'c': 1, 'e': {'f': 6, 'h': {'j': 3}}}
a2 = {'a': 2, 'c': 2, 'd': 4, 'e': {'f': 6, 'g': 8, 'h': {'i': 10}}}
I am required to update a1 with any values it is missing from a2. The missing keys are given as a list within a list i.e. [['d'], ['e', 'g'], ['e', 'h', 'i']]
. The last item means you are adding a nested item to a1. What would be the most efficient way to go about this?
NB:
- The
dict.update()
method doesn't work because it overwrites existing keys ina1
- The output of the missing keys is coming from the deepdiff package, which I am using to get the difference between the two dicts
Expected Output
{'a': 2, 'b': 3, 'c': 1, 'e': {'f': 6, 'g': 8, 'h': {'j': 3, 'i': 10}}, 'd': 4}