I currently have the following data taken off my database (list of 4 dicts):
raw_data = [{'budget_id': 1, 'name': 'Maria', 'amount': 980, 'user': '10', 'gift': 'Phone', 'cost': 325}, {'budget_id': 1, 'name': 'Maria', 'amount': 980, 'user': '10', 'gift': 'Flower', 'cost': 195}, {'budget_id': 2, 'name': 'Scott', 'amount': 2100, 'user': '10', 'gift': 'Paris Trip', 'cost': 599}, {'budget_id': 2, 'name': 'Scott', 'amount': 2100, 'user': '10', 'gift': 'Ring', 'cost': 1200}]
I would like to automatically merge each dictionary sharing the same "budget_id" so that in the end I end up with the following (list of 2 dicts) :
final_data = [{'name': ['Maria'], 'cost': [195, 325], 'gift': ['Phone', 'Flower'], 'budget_id': [1], 'user': ['10'], 'amount': [980]}, {{'name': ['Scott'], 'cost': [599, 1200], 'gift': ['Paris Trip', 'Ring'], 'budget_id': [2], 'user': ['10'], 'amount': [2100]}
The idea is that it should not be hardcoded as the amount of incoming dictionary from the website will gradually move and reduce overtime.
I so far have managed to find a hardcoded solution allowing me to merge the first and second dictionary successfully :
Merge_Init = {}
for key in (fibud.keys() | sebud.keys()):
if key in final_data[0]: Merge_Init.setdefault(key, []).append(final_data[0][key])
if key in final_data[1]: Merge_Init.setdefault(key, []).append(final_data[1][key])
print(Merge_Init)
final_merge = {a:list(set(b)) for a, b in Merge_Init.items()}
print("New Dict without Duplicates:", final_merge)
Resulting in :
New Dict without Duplicates: {'user': ['10'], 'gift': ['Phone', 'Flower'], 'name': ['Maria'], 'amount': [980], 'budget_id': [1], 'cost': [195, 325]}
Note that on this occasion, the cost of the gifts inverted themselves somewhat, the cost should be [325, 195].
Can you please assist in finding a solution to loop through each budget and merge them when they share the same budget_id without any hardcoded solution like "final_data[0]" while keeping data integrity?
Thanks a lot !