Home > Software design >  Merge List of dicts based on common key
Merge List of dicts based on common key

Time:11-10

I have the following list of dicts:

[{'key1': 'fixed_value', 'validlink': ['dynamic_value']}, {'key1': 'fixed_value', 'invalidlink':   ['dynamic_value']}]

I want to join the elements in the following manner(based on key 1 match):

[{'key1': 'fixed_value', 'validlink': ['dynamic_value'], 'invalidlink': ['dynamic_value']}]

I am currently using the following code but it only joins one key: I have tried appending both "validlink" & "invalidlink with no luck.

out_a.setdefault(v['key1'], []).append(v['validlink'])
new_dict = list(map(lambda x: dict(zip(('key1', 'validlink'), x)), out_a.items()))

CodePudding user response:

You can use a dict of dicts to keep updating dicts of the same key with new items:

merged = {}
for d in lst:
    merged.setdefault(d['key1'], {}).update(d)
print(list(merged.values()))

Given your sample input as lst, this outputs:

[{'key1': 'fixed_value', 'validlink': ['dynamic_value'], 'invalidlink': ['dynamic_value']}]

Demo: https://replit.com/@blhsing/SentimentalLightgreenSecurity

  • Related