首页 > 解决方案 > 提取与其他字典匹配的字典数据

问题描述

我有两本字典,一本是原版的,另一本是参考的。我想将参考字典键与原始字典键匹配,并提取所有这些键,即参考中存在的原始值。例如

original_dict = {
    'a': {
        '1': [1, 2, 3, 4, 5]
    },
    'b': {
        '1': {
            'A': [1, 2, 3, 4]
        }
    },
    'c': {
        '3': [1]
    }
}

和参考字典

reference_dict = {
    'a': {
        '2': [1, 2, 3]
    },
    'b': {
        '1': {
            'A': []
        }
    },
    'c': {
        '3': []
    }
}

这是提取的字典。

extracted_dict = {
    'b': {
        '1': {
            'A': [1, 2, 3, 4]
        }
    },
    'c': {
        '3': [1]
    }
}

在这里你可能已经注意到我不关心引用字典的值。我想要的只是原始字典的值。

标签: pythondictionary

解决方案


您可以使用递归来完成此操作:

def merge(value_dict, key_dict):
    ret = {}
    for key, subdict in key_dict.items():
        if key in value_dict:
            if not isinstance(value_dict[key], dict):
                # we found a value so don't keep recursing
                ret[key] = value_dict[key]
            else:
                # found another dict so merge subdicts
                merged = merge(value_dict[key], subdict)
                if len(merged) > 0:
                    ret[key] = merged
    return ret

merge(original_dict, reference_dict)

推荐阅读