Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Appending items in a nested python dictionary

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading