I have a nested python dictionary in the following format
{"exist":{"name":["a","b"],"country":["US"],"team":["SP","FR"]}, "not_exist":{}}
I want to append the following dictionary to the above one:
{"exist":{"age":[23,43,45],"sports":["football","rugby"]}, "not_exist":{"title":["Mr","Ms"]}}
So that the resulting dictionary looks like
{"exist":{"name":["a","b"],"country":["US"],"team":["SP","FR"],"age":[23,43,45],"sports":["football","rugby"]},
"not_exist":{"title":["Mr","Ms"]}}
I tried with update method, but its not working.
>Solution :
You can also use | operator (for python 3.9+) between dicts:
dct1 = {"exist":{"name":["a","b"],"country":["US"],"team":["SP","FR"]}, "not_exist":{}}
dct2 = {"exist":{"age":[23,43,45],"sports":["football","rugby"]}, "not_exist":{"title":["Mr","Ms"]}}
output = {k: v | dct2[k] for k, v in dct1.items()}
print(output)
# {'exist': {'name': ['a', 'b'], 'country': ['US'], 'team': ['SP', 'FR'], 'age': [23, 43, 45], 'sports': ['football', 'rugby']},
# 'not_exist': {'title': ['Mr', 'Ms']}}
For python with version lower than 3.9, you can use:
for k, v in dct2.items():
dct1[k].update(v)
print(dct1)
Note that this modifies your original dct1.