如何合并字典列表中具有相同id的字典
Here are a few practical ways to combine your list of dictionaries into the desired structure, depending on your use case:
1. Temporary Dictionary Accumulation (No External Libraries)
This is the most straightforward approach—perfect if you want to avoid adding dependencies. We'll use a temporary dictionary to group entries by id, then merge all key-value pairs for each id.
list_of_dicts = [ {"id": 1, "color_positive": "green"}, {"id": 1, "color_negative": "red"}, {"id": 2, "color_positive": "blue"}, {"id": 2, "color_negative": "yellow"}, ] merged_dict = {} for item in list_of_dicts: item_id = item["id"] # Initialize entry if id doesn't exist yet if item_id not in merged_dict: merged_dict[item_id] = {"id": item_id} # Merge the current item's key-value pairs into the entry merged_dict[item_id].update(item) # Convert the values of our temp dict back to a list result = list(merged_dict.values()) print(result)
Pros: Simple to understand, efficient for most small-to-medium datasets, no extra installs needed.
Cons: None for basic use cases.
2. Using itertools.groupby (Functional Style)
If you prefer a more functional approach, itertools.groupby can work—but note it requires sorting the list first (since it only groups consecutive elements with the same key).
from itertools import groupby from operator import itemgetter list_of_dicts = [ {"id": 1, "color_positive": "green"}, {"id": 1, "color_negative": "red"}, {"id": 2, "color_positive": "blue"}, {"id": 2, "color_negative": "yellow"}, ] # Sort the list by id first (required for groupby) sorted_list = sorted(list_of_dicts, key=itemgetter("id")) merged = [] # Group entries by id for id_key, group in groupby(sorted_list, key=itemgetter("id")): combined = {"id": id_key} # Merge all dictionaries in the current group for entry in group: combined.update(entry) merged.append(combined) print(merged)
Pros: Clean functional pattern, fits well if you're already using itertools in your code.
Cons: Adds an O(n log n) sorting step (negligible for small lists, but worth noting for large datasets).
3. Using Pandas (For Larger Datasets)
If you're working with bigger datasets or already using pandas in your project, this method is extremely concise.
import pandas as pd list_of_dicts = [ {"id": 1, "color_positive": "green"}, {"id": 1, "color_negative": "red"}, {"id": 2, "color_positive": "blue"}, {"id": 2, "color_negative": "yellow"}, ] # Convert list to DataFrame df = pd.DataFrame(list_of_dicts) # Group by id and take the first non-null value for each column merged_df = df.groupby("id").first().reset_index() # Convert back to list of dictionaries result = merged_df.to_dict("records") print(result)
Pros: Super concise, handles large datasets efficiently, easy to extend if you add more columns later.
Cons: Requires installing pandas (pip install pandas), which is overkill for tiny lists.
内容的提问来源于stack exchange,提问作者Ilya Babkov

