Home > Back-end >  Appending items in a nested python dictionary
Appending items in a nested python dictionary

Time:06-29

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.

CodePudding user response:

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.

CodePudding user response:

You can traverse the second dictionary and append all those values to the first one as follows:

d = {"exist":{"name":["a","b"],"country":["US"],"team":["SP","FR"]}, "not_exist":{}}
d1 = {"exist":{"age":[23,43,45],"sports":["football","rugby"]}, "not_exist":{"title":["Mr","Ms"]}}

for i in list(d1["exist"].keys()):
    d["exist"][i] = d1["exist"][i]
print(d1)

Output:

{'exist': {'age': [23, 43, 45], 'sports': ['football', 'rugby']}, 'not_exist': {'title': ['Mr', 'Ms']}}

CodePudding user response:

dict1 = {"exist":{"name":["a","b"],"country":["US"],"team":["SP","FR"]}, "not_exist":{}}
dict2 = {"exist":{"age":[23,43,45],"sports":["football","rugby"]}, "not_exist":{"title":["Mr","Ms"]}}


dict1["exist"].update(dict2["exist"])
dict1["not_exist"].update(dict2["not_exist"])
print(dict1)

This simple code snippet did the trick for me?

Output:

{'exist': {'name': ['a', 'b'], 'country': ['US'], 'team': ['SP', 'FR'], 'age': [23, 43, 45], 'sports': ['football', 'rugby']}, 'not_exist': {'title': ['Mr', 'Ms']}}
  • Related