在python中将dict2添加到dict1

时间:2014-11-14 06:21:43

标签: python recursion

说我有两个嵌套的词组。

dict1 = {"good authors": {"john" : {}, "jack" : {}}, "average authors" : {"kim" : {}, "peter" : {}} }

然后

dict2 = {"john" : {{"2008" : "book1"}, {"2009" : "book2"}}, "peter" : {{"2008" : "book3"}, {"2009" : "book4"}}}

如何递归地将dict2添加到dict1?

结果如下:

{"good authors": {"john" : {{"2008" : "book1"}, {"2009" : "book2"}}, "jack" : {}}, "average authors" : {"kim" : {}, "peter" : {{"2008" : "book3"}, {"2009" : "book4"}}} }

1 个答案:

答案 0 :(得分:0)

首先,list可能需要dict2作为值。

我尝试使用此

>>> dict1 = {"good authors": {"john" : {}, "jack" : {}}, "average authors" : {"kim" : {}, "peter" : {}} }

>>> dict2 = {"john" : [{"2008" : "book1"}, {"2009" : "book2"}], "peter" : [{"2008" : "book3"}, {"2009" : "book4"}]}
>>> for key, value in dict1.items():
...     for dict2key, dict2value in dict2.items():
...         if dict2key in value:
...             value[dict2key] = dict2value
...
>>> dict2
{'john': [{'2008': 'book1'}, {'2009': 'book2'}], 'peter': [{'2008': 'book3'}, {'2009': 'book4'}]}

可能有帮助