1

I want to use an api and would need to put my dataframe in a dictionary format first. The dataframe df that looks like this:

    OrigC  OrigZ  OrigN Weigh  DestC   DestZ    DestN
0      PL     97    TP    59     DE      63       SN

Exepected output of the first row:

{"section":[
    {"location":
        {
        "zipCode":
            {"OrigC": "PL",
            "OrigZ":"97"},
        "location": {"id": "1"},
        "OrigN": "TP"
            },
    "carriageParameter":
        {"road":
            {"truckLoad": "Auto"}
        },
    "load":
        {"Weigh": "59",
        "unit": "ton",
        "showEmissionsAtResponse": "true"
        }
    },
    {"location":
        {
        "zipCode":
            {"DestC": "DE",
            "DestZ":"63"},
        "location": {"id": "2"},
        "DestN": "SN"
            },
    "carriageParameter":
        {"road":
            {"truckLoad":"Auto"}
        },
    "unload":
        {"WEIGHTTONS":"59",
        "unit": "ton",
        "showEmissionsAtResponse": "true"
        }
    }]}

Note that there is static information in the dictionary that doesn't require any change.

How can this be done in Python?

1 Answer 1

3

You can use iterrows.

dic = {}
dic['section'] = []
for ix, row in df.iterrows():
    
    in_dict = {
        'location': {
            'zip_code': {
                'OrigC': row['OrigC'],
                'OrigZ': row['OrigZ'],
                },
            'location': {'id': ix+1}, # I am guessing here.
            'OrigN': 'TP',  
        },
        'CarriageParameter': {
            'road': {
                'truckLoad': 'Auto'}
            },
        'load': {
            'Weigh': str(row['Weigh']),
        } 
        }
    
    
    dic['section'].append(in_dict)

Note that this is not the entire entry, but I think it is clear enough to illustrate the idea.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks @warped, i tried the code, executed but nothing is printed on the ouput, there is no errors showed
What would you like to print?
the dictionary structure as described in the expected output
try print(dic) ?
for prettier prints you can check out pprint. In your case: import pprint and then pprint.pprint(dic)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.