我有这个片段
dict_a = {'key_1_lv_1': {'key_1': 'value_1'},
'key_2_lv_1': {'key_1_lv_2': 'value_1', 'key_2_lv_2': 'value_2', 'key_3_lv_2': 'value_3'},
}
dict_b = {'key_1_lv_1': {'key_1': 'value_1'},
'key_2_lv_1': {'key_1_lv_2': 'new_value'},
}
当我执行这一行时:
dict_a.update(dict_b)
并打印dict_a['key_2_lv_1'],它给了我:
{'key_1_lv_2': 'new_value'}, only. The other 2 key-value pairs are missing,, but i need them.
如果字典没有嵌套,我会得到其他 2 个键值对。 那么是否有任何巧妙的解决方案来获取嵌套字典中缺失的键值?
答案 0 :(得分:1)
代码:
dict_a = {'key_1_lv_1': {'key_1': 'value_1'},
'key_2_lv_1': {'key_1_lv_2': 'value_1', 'key_2_lv_2': 'value_2', 'key_3_lv_2': 'value_3'},
}
dict_b = {'key_1_lv_1': {'key_1': 'value_1'},
'key_2_lv_1': {'key_1_lv_2': 'new_value'},
}
for k,v in dict_b.items():
dict_a[k] = {**dict_a.get(k,{}),**v}
print(dict_a)
结果:
{'key_1_lv_1': {'key_1': 'value_1'}, 'key_2_lv_1': {'key_1_lv_2': 'new_value', 'key_2_lv_2': 'value_2', 'key_3_lv_2': 'value_3'}}
答案 1 :(得分:1)
您可以递归更新:
def recursive_update(d1, d2):
for key in d2:
# Check if the key exists on both dicts and merge them if they do
if key in d1 and isinstance(d1[key], dict) and isinstance(d2[key], dict):
# Recursively call the same function
recursive_update(d1[key], d2[key])
# You can add other conditions for merging lists or other data types here too if you want
else:
d1[key] = d2[key]
# Note this function works in place, so there is no return
用法:
recursive_update(dict_a, dict_b)
如果您确定您的数据结构将是一个具有 1 级嵌套的 dicts dict,@leaf_yakitori 的答案也将起作用并且更加简洁。如果某些值不是字典或嵌套超过 2 级,则此函数起作用。