将两个字典与嵌套字典相加

时间:2021-01-13 14:17:58

标签: python dictionary

我有两本像这样的字典:

first_dict = {"key": {"key": {"a2": x, "a3": y, "key": {"key": 1, "key": 2}}}}
second_dict = {"key": {"key": {"a2": x, "a3": y, "key": {"key": 3, "key": 4}}}}

我想对这些字典求和,但将 a2 和 a3 键保留在最终结果中,以便最终结果如下所示:

result_dict = {"key": {"key": {"a2": x, "a3": y, "key": {"key": 4, "key": 6}}}}

我有一个递归的方法来总结这些字典:

def sum_dicts(first_dict, second_dict):
    if isinstance(first_dict, dict):
        return {k: sum_dicts(first_dict[k], second_dict[k]) for k in first_dict}

    return first_dict + second_dict

但是我在理解如何将这些 a2 和 a3 键保持在最终结果中时遇到了一些麻烦,因为我知道它们在两个字典中的值相等[并且无需验证]

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

在对值求和之前,您可以检查最后看到的两个键的名称是否符合特定条件:

first_dict = {"key": {"key": {"a2": 1, "a3": 2, "key": {"key_1": 1, "key_2": 2}}}}
second_dict = {"key": {"key": {"a2": 1, "a3": 2, "key": {"key_1": 3, "key_2": 4}}}}
def get_sum(d1, d2, name = None):
  if not any([isinstance(d1, dict), isinstance(d2, dict)]):
     return d1 if not name.startswith('key_') else d1 + d2
  return {i:get_sum(d1.get(i, {}), d2.get(i, {}), i) for i in set(d1)|set(d2)}

print(get_sum(first_dict, second_dict))

输出:

{'key': {'key': {'a3': 2, 'a2': 1, 'key': {'key_1': 4, 'key_2': 6}}}}