Merging arbitrarily nested dictionaries, maintaining keys, and putting results with the same key in a list in Python

て烟熏妆下的殇ゞ 提交于 2020-01-17 07:19:08

问题


This is my input:

dict1 = { 'home': 'Documents'}
dict2 = { 'home': {'Documents': 'projects'}}
dict3 = {'projects': 'test.py'}
dict4 = {'projects': 'test2.py'}
dict5 = {'Documents': 'old_memes'}
dict6 = {'old_memes': 'me_gusta.jpg'}
dict7 = {'old_memes': 'fml.jpg'}

My goal is to have an output of a single dictionary, like this:

final_dict = {'home': 
                      {'Documents':
                                   [
                                    {'projects': ['test.py','test2.py']},
                                    {'old_memes':['me_gusta.jpg','fml.jpg']}
                                   ]
                       }
              }

I searched around, but couldn't find nothing that do this. I tried using defaultdict but it didn't work either. If this is not possible with dictionaties, can you point me another data structure that can do this(and be converted to a JSON)?

来源:https://stackoverflow.com/questions/43641813/merging-arbitrarily-nested-dictionaries-maintaining-keys-and-putting-results-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!