交换两个嵌套的字典

时间:2019-10-17 00:01:37

标签: python

我正在尝试在两个二叉树之间交换节点,这些二叉树被表示为嵌套字典。我试图通过使用一个函数来实现这一点,该函数接受dict和键列表,对其进行深层处理,然后返回嵌套的dict。例如

def deep_get(dictionary, keys, default=None):
    """ By Yuda Prawira
    Source: https://stackoverflow.com/questions/25833613/python-safe-method-to-get-value-of-nested-dictionary"""
    return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("."), dictionary)

但是,每当我将其分配给变量并尝试进行基本交换时,原始字典便保持不变:

a = deep_get(tree1, "left.right.left")
b = deep_get(tree2, "left.right")
c = a.copy()
a.clear()
a.update(b)
b.clear()
b.update(c)

是否有更简单的方法来完成此操作,还是我必须创建一个包装字典的树类?

样本输入:

tree1 = {'left': {'left': 5, 'op': 'sin', 'right': 1}, 'op': 'cos', 'right': {'op': 'sin', 'right': 3}}
tree2 = {'left': {'left': 1, 'op': 'sin', 'right': 2}, 'op': 'tan', 'right': {'left': 1, 'op': 'sin', 'right': 4}}

首先,我从tree1和tree2中随机选择一个要交换的节点。假设我想将tree1的第一级左分支与tree2的第二级右分支交换。然后交换后的树应该像:

tree1 = {'left': {'left': 1, 'op': 'sin', 'right': 4}, 'op': 'cos', 'right': {'op': 'sin', 'right': 3}}
tree2 = {'left': {'left': 1, 'op': 'sin', 'right': 2}, 'op': 'tan', 'right': {'left': 5, 'op': 'sin', 'right': 1}}

0 个答案:

没有答案
相关问题