python - 如何合并具有相似键的字典列表中的字典
问题描述
我有一个这样的字典列表:
list_of_dicts = [
{"id": 1, "color_positive": "green"},
{"id": 1, "color_negative": "red"},
{"id": 2, "color_positive": "blue"},
{"id": 2, "color_negative": "yellow"},
]
我想做:
[
{"id": 1, "color_positive": "green", "color_negative": "red"},
{"id": 2, "color_positive": "blue", "color_negative": "yellow"},
]
有什么办法吗?
解决方案
你可以用defaultdict
这个。
from collections import defaultdict
result = defaultdict(dict)
for item in list_of_dicts:
result[item["id"]].update(**item)
result = list(result.values())
print(result)
输出:
[{'id': 1, 'color_positive': 'green', 'color_negative': 'red'}, {'id': 2, 'color_positive': 'blue', 'color_negative': 'yellow'}]
推荐阅读
- postgresql - 如何使用 UTL_MAIL.send 将 oracle PL/SQL 转换为 PL/SQL 中的电子邮件到 postgresql PL/SQL 代码?
- emacs - emacs 的多个实例覆盖recentf-list
- python - python中的包和模块导入
- excel - 使用 Selenium WebDriver VBA 从表中提取条件值
- python - 如何在 Python 中更改相机识别的颜色
- c# - 在 C# 中的这个小问题中,递归是如何工作的?
- c++ - 如果“struct”和“class”是同一个东西,那么为什么模板中只使用“class”
不是“结构”? - python - 如何将 python 目录包含到 CMakeList.txt 文件中
- javascript - Angular mat-pagination onClick 下一页出现黑边
- javascript - H5和JSON模型的输出不同