I want merge two dictionaries first over second, meaning the first dictionary doesn't lose its previous values and only the missing key values are added into first.
Original = {key1: { key2:[{ key3: y1 , key5: z1 , key6 [{key7: n1}]}]}}
Example = {key1: { key2:[{ key3: None , key4: None ,key5: None , key6 [{key7: None,key8:None}]}]}}
def update2(final, first):
for k, v in first.items():
if isinstance(v, str):
final[k] = v
elif k in final:
if isinstance(final[k], dict):
final[k].update2(first[k])
else:
final[k] = first[k]
else:
final[k] = first[k]
final_json = update2(Example['key1'], Original['key1'])
print(final_json)
#returns only Original not appended output
def update3(right,left):
d = dict()
for key,val in left.items():
d[key]=[val]
for key,val in right.items():
if key not in d.keys():
d[key].append(val)
else:
d[key]=[val]
final_json = update3(Example['key1'], Original['key1'])
print(final_json) #returns None
Expected output:
{key1: { key2:[{ key3: y1 , key4: None ,key5: z1 , key6 [{key7: n1,key8:None}]}]}}
I have referred many stackoverlfow posts but nothing is working since it has to be iterated at multiple levels.
Set default values according to JSON schema automatically
how to merge two dictionaries based on key but include missing key values in python?
Merge two dictionaries and persist the values of first dictionaries
My goal is to add default values for missing keys from example file.I am beginner to Python.