I have multiple dictionaries in a list, and the structure of the dictionaries are like this:
dict1 = {'first': [{'att1': 'abc',
'att2': '123',
'att3': 'abc123'},
{'att1': 'abc',
'att2': '123',
'att3': 'abc123'}],
'second': [{'att1': 'abc',
'att2': '123'},
{'att1': 'abc',
'att2': '123'}],
'third': [{'att4': 'bca'}]}
dict2 = {'first': [{'att1': 'abc',
'att2': '123',
'att3': 'abc123'},
{'att1': 'abc',
'att2': '123',
'att3': 'abc123'}],
'second': [{'att1': 'abc',
'att2': '123'},
{'att1': 'abc',
'att2': '123'}]}
dict_list = [dict1, dict2]
I want to merge the dictionaries in the list based on the highest level keys 'first', 'second' and 'third' if they exist in the dictionaries, so my desired output would look like this:
merged = {'first': [{'att1': 'abc',
'att2': '123',
'att3': 'abc123'},
{'att1': 'abc',
'att2': '123',
'att3': 'abc123'},
{'att1': 'abc',
'att2': '123',
'att3': 'abc123'},
{'att1': 'abc',
'att2': '123',
'att3': 'abc123'}],
'second': [{'att1': 'abc',
'att2': '123'},
{'att1': 'abc',
'att2': '123'},
{'att1': 'abc',
'att2': '123'},
{'att1': 'abc',
'att2': '123'}],
'third': [{'att4': 'bca'}]}
The dictionaries are created from dataframes using the pandas function to_dict. If merging json objects based on keys is easier or just as easy, this is also an option as i could use to_json instead. Is there any smart pythonic way of doing this? Any help is appreciated.