python - 提取与其他字典匹配的字典数据
问题描述
我有两本字典,一本是原版的,另一本是参考的。我想将参考字典键与原始字典键匹配,并提取所有这些键,即参考中存在的原始值。例如
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]
}
}
在这里你可能已经注意到我不关心引用字典的值。我想要的只是原始字典的值。
解决方案
您可以使用递归来完成此操作:
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)
推荐阅读
- google-drive-api - 有没有办法使用 Google Drive API 更改文件创建者?
- node.js - Stripe later payment direct charges, create token error, The customer must have an active payment source attached
- c++ - 键已存在于 unordered_map 中,但“查找”返回未找到
- java - 支持“RPC/编码”格式的 Java 14 客户端生成器的替代(Axis 1.4)WSDL
- sql - Vertica 中带有 Qualify 子句的 ROW_NUMBER()
- java - 如何绘制在 try/catch 中创建的图像?
- mapbox - 停止 Mapbox GL JS 缩放事件
- sparql - 没有 URI 的 SPARQL 查询
- spring-security - 记录 Spring Security OAuth2 身份验证失败的推荐方法是什么?
- ios - 我可以实现将视频数据从 Mac OS 传输到 iOS 设备吗?