Nico44044
Nico44044

Reputation: 411

Python Merge 2 DICT objects if matching id within a list with separators

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.

Upvotes: 1

Views: 63

Answers (2)

Patryk Opiela
Patryk Opiela

Reputation: 37

I suggest to keep id_company in list and instead of creating new disc, add new field in dict1 for company name.

Now the code will look like this,

peopleDict = [
{
    'id_contact': 1, 
    'name': 'Rick',
    'company_name': [],
 },
{
    'id_contact': 9, 
    'name': 'John',
    'company_name': [],
}
]

companyDict = [
    {
        'id_company': [1,3,4,11], 
        'company_name': 'Nike'
        },
    {
        'id_company': [1,2,9], 
        'company_name': 'Adidas'
    }
]

for person in peopleDict:
    for company in companyDict:
        if person.get('id_contact') in company.get('id_company'):
            person['company_name'].append(company.get('company_name'))

print(peopleDict)

Upvotes: 1

mozway
mozway

Reputation: 262214

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'}]

Upvotes: 1

Related Questions