Python 如何将词典列表合并到词典中
我有一个python字典列表,如下所示:Python 如何将词典列表合并到词典中,python,list,dictionary,group-by,Python,List,Dictionary,Group By,我有一个python字典列表,如下所示: [{'George': {u'finance': {u'investing': {u'venture capital': 'Peter'}}}}, {'George': {u'finance': {u'investing': {u'venture capital': 'John'}}}}, {'George': {u'finance': {u'investing': {u'venture capital': 'Kate'}}}}] merged_d
[{'George': {u'finance': {u'investing': {u'venture capital': 'Peter'}}}},
{'George': {u'finance': {u'investing': {u'venture capital': 'John'}}}},
{'George': {u'finance': {u'investing': {u'venture capital': 'Kate'}}}}]
merged_dict = {}
for d in your_list_of_dicts:
for k in d:
if k not in merged_dict.keys():
merged_dict[k] = d[k]
merged_dict[k]['finance']['investing']['venture capital'] = [merged_dict[k]['finance']['investing']['venture capital']]
else:
merged_dict[k]['finance']['investing']['venture capital'].append(d[k]['finance']['investing']['venture capital'])
我想分组,所以最终结果是:
{'George': {u'finance': {u'investing': {u'venture capital': ['Peter','John','Kate'}}}}
如何按此词典列表进行分组 到目前为止你试过什么 如果您的数据结构如上面的示例所示是固定的,您可以尝试以下方法:
[{'George': {u'finance': {u'investing': {u'venture capital': 'Peter'}}}},
{'George': {u'finance': {u'investing': {u'venture capital': 'John'}}}},
{'George': {u'finance': {u'investing': {u'venture capital': 'Kate'}}}}]
merged_dict = {}
for d in your_list_of_dicts:
for k in d:
if k not in merged_dict.keys():
merged_dict[k] = d[k]
merged_dict[k]['finance']['investing']['venture capital'] = [merged_dict[k]['finance']['investing']['venture capital']]
else:
merged_dict[k]['finance']['investing']['venture capital'].append(d[k]['finance']['investing']['venture capital'])
可能是复制品我很确定我看到了。如果字典的数量不是固定的,那么应该使用递归。如果没有,那么你可以得到最低的数据,检查差异并合并。正如我在你的尝试中看到的,你可以使用已知的“金融”或“投资”。但事实是,我只展示了列表中的一小部分。我有许多不同的钥匙,我想能够结合他们以及。