简体   繁体   English

在嵌套的 python 字典中附加项目

[英]Appending items in a nested python dictionary

I have a nested python dictionary in the following format我有以下格式的嵌套 python 字典

{"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.我尝试使用update方法,但它不起作用。

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']}}

You can also use |您也可以使用| operator (for python 3.9+) between dicts:字典之间的运算符(对于python 3.9+):

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:对于版本低于 3.9 的 python,可以使用:

for k, v in dct2.items():
    dct1[k].update(v)
print(dct1)

Note that this modifies your original dct1 .请注意,这会修改您原来的dct1

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']}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM