如何根据字典中的键合并数据,同时保留Python输出中的键?



存在如下格式的字典:[List contains Dictionaries]

[{'ID': '743987', 'Information': 'Anime is the Best'},
{'ID': '743987','Information': 'Python is the Best'}]

所需输出:

[
{'ID': '743987','Information': ['Anime is the Best','Python is the Best']}
]

我见过其他解决方案,但似乎没有一个产生以下输出:

({'ID': '743987','Information': ['Anime is the Best','Python is the Best']})

ID' and 'Information'作为输出的一部分。

如何进行?

您可以使用defaultdict

from collections import defaultdict
res = defaultdict(list)
a = [{'ID': '743987', 'Information': 'Anime is the Best'},
{'ID': '743987','Information': 'Python is the Best'}]
for i in a:
for key in i.keys():
if key == 'ID':
res[key] = i[key]
else:
res[key].append(i[key])
print(dict(res))

输出
{'ID': '743987', 'Information': ['Anime is the Best', 'Python is the Best']}

相关内容

  • 没有找到相关文章

最新更新