基于dict1结构骨架与dict2对应值创建嵌套字典
解决方案:基于指定结构从字典提取对应数据
嘿,这个需求我之前也碰到过,刚好可以用递归的方式完美解决——毕竟嵌套字典的层级不确定,递归是最省心的处理方式。
核心思路就是严格遵循dict1的结构骨架,递归遍历每一层键,从dict2里提取对应键的值,完全忽略dict2里不在dict1结构中的键。下面是具体的实现代码:
def build_structured_dict(struct, data): result = {} for key, value in struct.items(): # 如果当前结构是嵌套字典,递归处理子层级 if isinstance(value, dict): # 从data里取对应键的子字典,没有的话传空字典避免报错 result[key] = build_structured_dict(value, data.get(key, {})) else: # 普通键,从data里取值,不存在则保留原结构的默认值(或者改成None) result[key] = data.get(key, value) return result
测试示例
我们用你需求里的场景来测试一下:
# 你的结构骨架dict1 dict1 = { 'user': { 'basic': { 'name': '', 'age': '' }, 'contact': { 'email': '' } }, 'settings': { 'theme': '' } } # 包含额外键值对的dict2 dict2 = { 'user': { 'basic': { 'name': 'Alice', 'age': 30, 'gender': 'female' # 这个键不在dict1里,会被忽略 }, 'contact': { 'email': 'alice@example.com', 'phone': '123456' # 不在结构中,忽略 }, 'extra_info': 'random text' # 不在dict1结构里,忽略 }, 'settings': { 'theme': 'dark', 'notifications': True # 忽略 }, 'unrelated_key': 'some value' # 完全不在结构中,忽略 } # 生成结果字典 final_dict = build_structured_dict(dict1, dict2) print(final_dict)
输出结果
运行后你会得到完全匹配dict1结构的字典,只保留了dict2里对应键的值:
{ 'user': { 'basic': { 'name': 'Alice', 'age': 30 }, 'contact': { 'email': 'alice@example.com' } }, 'settings': { 'theme': 'dark' } }
小调整说明
如果遇到dict1里的键在dict2中不存在的情况,上面的代码会保留dict1里的默认值(比如示例里的空字符串)。如果你希望这种情况返回None,只需要把代码里的data.get(key, value)改成data.get(key)就行。
内容的提问来源于stack exchange,提问作者Amarula
相关产品推荐
相关产品推荐

