简体   繁体   中英

How to merge dicts in list of dicts with similar keys

I have a list of dicts like this:

list_of_dicts = [
    {"id": 1, "color_positive": "green"},
    {"id": 1, "color_negative": "red"},
    {"id": 2, "color_positive": "blue"},
    {"id": 2, "color_negative": "yellow"},
]

And I want to make:

[
    {"id": 1, "color_positive": "green", "color_negative": "red"},
    {"id": 2, "color_positive": "blue", "color_negative": "yellow"},
]

Are there any ways?

You can use defaultdict for this.

from collections import defaultdict

result = defaultdict(dict)

for item in list_of_dicts:
    result[item["id"]].update(**item)
result = list(result.values())
print(result)

Output:

[{'id': 1, 'color_positive': 'green', 'color_negative': 'red'}, {'id': 2, 'color_positive': 'blue', 'color_negative': 'yellow'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM