我想将这两个字典合并到“family”键上。我正在研究一个递归函数来实现合并,但我想知道是否没有更好的方法。我正在查看 collections.chainmap,它看起来很接近我正在做的事情,但可能有点矫枉过正。
输入:
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::
输出:
xe-3/0/2:
description:
unit:
'0':
family:
inet4:
address: 10.0.0.1
inet6:
address: FE80::
我试图通过使用更多技巧和内置函数来提高 Python 性能,但我认为我没有正确的方法来发现我可以做什么,而不是堆叠一堆 for 循环。
谢谢
编辑:
这个函数非常适合我的情况,但有以下假设:
D1 永远会更深、更宽。 D2 始终只有一棵树。
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)
最佳答案
您可以将递归与collections.defaultdict
一起使用:
import yaml, collections
d1 = yaml.safe_load('''xe-3/0/2:
description:
unit:
'0':
family:
inet4:
address: 10.0.0.1''')
d2 = yaml.safe_load('''xe-3/0/2:
description:
unit:
'0':
family:
inet6:
address: FE80''')
def merge(*args):
if any(not isinstance(i, dict) for i in args):
return args[0] if len(args) == 1 else list(args)
d = collections.defaultdict(list)
for i in args:
for a, b in i.items():
d[a].append(b)
return {a:merge(*b) for a, b in d.items()}
print(yaml.dump(merge(d1, d2)))
输出:
xe-3/0/2:
description:
unit:
'0':
family:
inet4:
address: 10.0.0.1
inet6:
address: FE80
关于python - 如何合并两个字典,其中它们的树具有匹配的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68537390/