I want to transform to a specific nested dictionary format. The dataframe df looks like this:
OC OZ ON WT DC DZ DN
0 PL 97 TP 59 DE 63 DC
3 US 61 SU 9 US 95 SU
The expected output is this:
{'location':
{
'zipCode':
{'country': 'PL',
'code': '97'},
'location': {'id': '1'},
'longName': 'TP',
},
'CarriageParameter':
{'road':
{'truckLoad': 'Auto'}
},
'load':
{'weight': '59',
'unit': 'ton',
'showEmissionsAtResponse': 'true'
}
},
{'location':
{
'zipCode':
{'country': 'DE',
'code': '63'},
'location': {'id': '2'},
'longName': 'DC']
},
'CarriageParameter':
{'road':
{'truckLoad': 'Auto'}
},
'unload': {
'weight': '59'),
'unit': 'ton',
'showEmissionsAtResponse': 'true'
}
}
I've tried this code below but i am only getting one part of the dictionary:
dic = {}
dic['section'] = []
for ix, row in df.iterrows():
in_dict1 = {
'location':
{
'zipCode':
{'country': row['OC'],
'code': row['OZ']},
'location': {'id': '1'},
'longName': row['ON'],
},
'CarriageParameter':
{'road':
{'truckLoad': 'Auto'}
},
'load':
{'weight': str(row['WT']),
'unit': 'ton',
'showEmissionsAtResponse': 'true'
}
},
in_dict2 = {'location':
{
'zipCode':
{'country': row['DC'],
'code': row['DZ']},
'location': {'id': '2'},
'longName': row['DN']
},
'CarriageParameter':
{'road':
{'truckLoad': 'Auto'}
},
'unload': {
'weight': str(row['WT']),
'unit': 'ton',
'showEmissionsAtResponse': 'true'
}
}
dic['section'].append(in_dict1)
the pretty print of the first row below:
{'section': [{'CarriageParameter': {'road': {'truckLoad': 'Auto'}},
'load': {'showEmissionsAtResponse': 'true',
'unit': 'ton',
'weight': '59'},
'location': {'location': {'id': '1'},
'longName': 'TP COLEP_GRABICA PL',
'zipCode': {'code': '97-306', 'country': 'PL'}}}]}
I would expect the second part of the dictionary it's kind of lost somewhere...
How to fix this issue ?
in_dict2to your list