In Python I have those 2 dicts objects :
dict1 = [{'id_contact': '1', 'name': 'Rick'},{'id_contact': '9', 'name': 'John'}]
dict2 = [{'id_company': ';1;3;4;11;', 'company_name': 'Nike'},{'id_company': ';1;2;9;', 'company_name': 'Adidas'}]
I would like to merge those 2 dicts to a new one to add the 'company_name'
if id_contact
of dict1 is found in id_company
in dict2.
If theres is several matches I would like to use ";" as a separator in 'company_name'
.
The expected result would be :
dictmerge = [{'id_contact': '1', 'name': 'Rick', 'company_name': 'Nike;Adidas'},{'id_contact': '9', 'name': 'John', 'company_name': 'Adidas'}]
Thanks for your help.
Initial note: dict1
and dict1
are lists (of dictionaries), not dictionaries.
You need a few steps, first loop over dict2
to aggregate the company names per ID, then flatten this as a string. Finally, loop over dict1
and add the missing key:
companies = {}
for d in dict2:
for i in d.get('id_company', '').strip(';').split(';'):
companies.setdefault(i, []).append(d['company_name'])
companies = {i: ';'.join(v) for i, v in companies.items()}
# {'1': 'Nike;Adidas', '3': 'Nike', '4': 'Nike', '11': 'Nike',
# '2': 'Adidas', '9': 'Adidas'}
for d in dict1:
d['company_name'] = companies.get(d['id_contact'])
print(dict1)
Output:
[{'id_contact': '1', 'name': 'Rick', 'company_name': 'Nike;Adidas'},
{'id_contact': '9', 'name': 'John', 'company_name': 'Adidas'}]