gpt4 book ai didi

python - 如何合并两个字典,其中它们的树具有匹配的键?

转载 作者:行者123 更新时间:2023-12-04 07:20:27 26 4
gpt4 key购买 nike

我想在他们相遇的地方合并这两个字典,在“家庭”键上。我正在研究一个递归函数来进行合并,但我想知道是否没有更好的方法。我正在查看 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com