'merge nested dictionary and list of dictionaries, python
I would like to combine two nested dictionaries that have a slight structure (one is a list of dictionaries and the other one is a nested dictionary). I would very much appreciate your help!
GPP_projects =
[{'CompanyId': 61149,
'Id': 44},
{'CompanyId': 61307,
'Id': 45}]
GPP_companies =
{61149: {
'Name': 'xyz',
'CompanyId': 61149},
61307: {
'Name': 'abc',
'CompanyId': 61307}}
#wanted outcome
GPP_combined =
[{'CompanyId': 61149,
'Id': 44,
'Name': 'xyz'}
{'CompanyId': 61307,
'Id': 45,
'Name': 'abc'}}]
Solution 1:[1]
You could use a pandas approach or you could simply do the following
GPP_combined = [{**data, **GPP_companies.get(data['CompanyId'], {})} for data in GPP_projects]
This will check if there is CompanyId in the GPP_companies dict, if so it will add it in. If there are no id in there GPP_companies it returns an empty dict which will do nothing.
Depending on what you want to do in the following cases:
- no
CompanyIdinGPP_companies? - if there are errors in
GPP_companieswhich means {**a, **b} will over write valid fields inGPP_projects
output
GPP_projects =[{'CompanyId': 61149,
'Id': 44},
{'CompanyId': 61307,
'Id': 45,}]
GPP_companies = {61149: {
'Name': 'xyz',
'CompanyId': 61149},
61307: {
'Name': 'abc',
'CompanyId': 61307}}
#wanted outcome
GPP_combined =[{'CompanyId': 61149,
'Id': 44,
'Name': 'xyz'},
{'CompanyId': 61307,
'Id': 45,
'Name': 'abc'}]
GPP_combined = [
{**data, **GPP_companies.get(data["CompanyId"], {})}
for data in GPP_projects
]
"""
>> GPP_combined
[{'CompanyId': 61149, 'Id': 44, 'Name': 'xyz'},
{'CompanyId': 61307, 'Id': 45, 'Name': 'abc'}]
"""
for python 2.7
for data in GPP_projects:
company_id = data['CompanyId']
company_obj = GPP_companies.get(company_id)
if company_rec:
data['Name'] = company_obj['Name']
This modified GPP_projects or you can do a copy to ensure that you are not modifying GPP_projects.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
