0

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:

  1. The dict.update() method doesn't work because it overwrites existing keys in a1
  2. 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}
Mwangi Kabiru
  • 423
  • 2
  • 10
  • Can you add the expected output also? – Kaushal Kumar Nov 09 '21 at 17:29
  • 2
    If you are already using `deepdiff`, [`deepdiff.Delta`](https://zepworks.com/deepdiff/current/delta.html#diff-to-load-in-delta) seems to be what you want. – Amadan Nov 09 '21 at 17:29
  • @KaushalKumar Thank you, I just did @Amadan `a1 + Delta(DeepDiff(a1, a2))` gives the same result as `a1.update(a2)` i.e. overwrites some keys – Mwangi Kabiru Nov 09 '21 at 17:44
  • For anyone interested, I resolved this using the solution [here](https://stackoverflow.com/a/7205107/10295795). However, I did a small edit i.e. skip the conflict exception and just pass to retain data in original dict. Thank you – Mwangi Kabiru Nov 09 '21 at 18:11

0 Answers0