Suppose we have 2 dictionaries:
a = {
"key1": "value1",
"key2": "value2",
"key3": {
"key3_1": "value3_1",
"key3_2": "value3_2"
}
}
b = {
"key1": "not_key1",
"key4": "something new",
"key3": {
"key3_1": "Definitely not value3_1",
"key": "new key without index?"
}
}
As a result of the merger, I need to get the following dictionary:
{
"key1": "not_key1",
"key2": "value2",
"key3": {
"key3_1": "Definitely not value3_1",
"key3_2": "value3_2",
"key": "new key without index?"
},
"key4": "something new"
}
I have this kind of code:
def merge_2_dicts(dict1, dict2):
for i in dict2:
if not type(dict2[i]) == dict:
dict1[i] = dict2[i]
else:
print(dict1[i], dict2[i], sep="\n")
dict1[i] = merge_2_dicts(dict1[i], dict2[i])
return dict1
It works and gives me the desired result, but I'm not sure if it can be done more simply. Is there an easier/shorter option?