Gomelsar BARO
Gomelsar BARO

Reputation: 180

From Dataframe to nested Dictionary in Python

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 ?

Upvotes: 1

Views: 71

Answers (1)

MrNobody33
MrNobody33

Reputation: 6483

It's because you didn't add the second dictionary, you could try this:

import pandas as pd
import io

s_e='''
    OC  OZ  ON  WT  DC  DZ  DN
0   PL  97  TP  59  DE  63  DC 
3   US  61  SU  9   US  95  SU
'''
df = pd.read_csv(io.StringIO(s_e), sep='\s\s+', parse_dates=[1,2], engine='python')

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)
    dic['section'].append(in_dict2)
    
print(dic['section'])

Output:

[{'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'}}, {'location': {'zipCode': {'country': 'US', 'code': 61}, 'location': {'id': '1'}, 'longName': 'SU'}, 'CarriageParameter': {'road': {'truckLoad': 'Auto'}}, 'load': {'weight': '9', 'unit': 'ton', 'showEmissionsAtResponse': 'true'}}, {'location': {'zipCode': {'country': 'US', 'code': 95}, 'location': {'id': '2'}, 'longName': 'SU'}, 'CarriageParameter': {'road': {'truckLoad': 'Auto'}}, 'unload': {'weight': '9', 'unit': 'ton', 'showEmissionsAtResponse': 'true'}}]

Upvotes: 2

Related Questions