Merge multiple dictionaries within a list by primary key

Following question:

I have a list of dictionaries like:

l = [{"primary_key": 5164, "attribute1": 2},
     {"primary_key": 5162, "attribute1": 3}, 
     {"primary_key": 5164, "attribute2": 3}] 

I want to join them into an output list, but merging the dictionaries that have the same primary-key as:

output_l = [{"primary_key": 5164, "attribute1": 2, "attribute2": 3},
            {"primary_key": 5162, "attribute1": 3}]

After searching a lot I did not find this question somewhere else. Sorry if it is a duplicate. It is very related to this question, but with only one list instead of multiple.

Answer

Create a dictionary where you store the ever growing dictionaries by their primary key. The following will work:

dicts = {}
for dct in l:
    dicts.setdefault(dct["primary_key"], {}).update(dct)

l = [*dicts.values()]
# [{'primary_key': 5164, 'attribute1': 2, 'attribute2': 3},
#  {'primary_key': 5162, 'attribute1': 3}]

Note that shared attribute name, the latest entry will “win”.