I'd like to merge these two dicts where they meet, on the "family" key. I'm working on a recursive function to make the merge happen but I wonder if there isn't a better way. I was looking at collections.chainmap and it seemed close that what I'm doing but perhaps overkill.
Input:
xe-3/0/2:
description:
unit:
'0':
family:
inet4:
address: 10.0.0.1
xe-3/0/2:
description:
unit:
'0':
family:
inet6:
address: FE80::
Output:
xe-3/0/2:
description:
unit:
'0':
family:
inet4:
address: 10.0.0.1
inet6:
address: FE80::
I'm trying to get better at python by using more tricks and built-in functions but I don't think I have the right approach for discovering what I can do instead of stacking a bunch of for loops.
Thanks,
EDIT:
This function works perfectly for my case, with the following assumptions:
D1 will always be deeper and wider. D2 will always have a single tree.
def join_dicts(d1, d2):
def recurse_join(d1, d2):
if not isinstance(d1, dict) and not isinstance(d2, dict):
return [d1, d2]
if not isinstance(d1, dict):
return {**{d1 : ""}, **d2}
if not isinstance(d2, dict):
return {**d1, **{d2 : ""}}
for key in d2:
if key not in d1:
return {**d1, **d2}
else:
d1[key] = recurse_join(d1[key], d2[key])
return d1
return recurse_join(d1, d2)