ARTICLE AD BOX
I have two lists of dictionaries in Python, and I need to merge them into a single list based on a shared key (e.g., id).
My Data:
Python
list_a = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Charlie'} ] list_b = [ {'id': 1, 'score': 90}, {'id': 2, 'score': 85}, {'id': 3, 'score': 92} ]What I want to achieve:
I want to combine them into one list where each dictionary contains all the keys:
Python
[ {'id': 1, 'name': 'Alice', 'score': 90}, {'id': 2, 'name': 'Bob', 'score': 85}, {'id': 3, 'name': 'Charlie', 'score': 92} ]What I've tried:
I currently use a nested for loop to find the matching IDs:
Python
result = [] for a in list_a: for b in list_b: if a['id'] == b['id']: combined = a.copy() combined.update(b) result.append(combined)While this works, my actual dataset has over 50,000 items, and this nested loop approach is $O(n^2)$, which is extremely slow.
My Question:
Is there a more "Pythonic" or efficient way to do this? I am looking for a solution that ideally runs in $O(n)$ time, perhaps using a dictionary for lookup or a specific feature of the Python Standard Library.
