首页 > 解决方案 > 如何合并具有相似键的字典列表中的字典

问题描述

我有一个这样的字典列表:

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"},
]

有什么办法吗?

标签: python

解决方案


你可以用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'}]

推荐阅读