Python pandas map dict keys to values
Question: I have a csv for input, whose row values I'd like to join into a new field.
This new field is a constructed url, which will then be processed by the
requests.post() method.

I am constructing my url correctly, but my issue is with the data object that
should be passed to requests. How can I have the correct values passed to
their proper keys when my dictionary is unordered? If I need to use an ordered
dict, how can I properly set it up with my current format?

Here is what I have:

    
    
    import pandas as pd
    import numpy as np
    import requests
    
    test_df = pd.read_csv('frame1.csv')
    
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    
    test_df['FIRST_NAME'] = test_df['FIRST_NAME'].astype(str)
    test_df['LAST_NAME'] =  test_df['LAST_NAME'].astype(str)
    test_df['ADDRESS_1'] = test_df['ADDRESS_1'].astype(str)
    test_df['CITY'] = test_df['CITY'].astype(str)
    
    test_df['req'] = 'site-url.com?' + '&FIRST_NAME=' + test_df['FIRST_NAME'] + '&LAST_NAME=' + \
        test_df['LAST_NAME'] + '&ADDRESS_1=' + test_df['ADDRESS_1'] + '&CITY=' + test_df['CITY']
    
    arr = test_df.values
    
    d = {'FIRST_NAME':test_df['FIRST_NAME'], 'LAST_NAME':test_df['LAST_NAME'],
        'ADDRESS_1':test_df['ADDRESS_1'], 'CITY':test_df['CITY']}
    
    test_df = pd.DataFrame(arr[0:, 0:], columns=d, dtype=np.str)
    data = test_df.to_dict()
    data = {k: v for k, v in data.items()}
    
    test_df['raw_result'] = test_df['req'].apply(lambda x: requests.post(x, headers=headers,
        data=data).content)
    
    test_df.to_csv('frame1_result.csv')
    

I tried to map values to keys with a dict comprehension, but the assignment of
a key like `FIRST_NAME` could end up mapping to values from an arbitrary field
like `test_df['CITY']`.


Answer: Not sure if I understand the problem correctly. However, you can give argument
to `to_dict` function e.g.

    
    
    data = test_df.to_dict(orient='records')
    

which will give you output as follows: `[{'FIRST_NAME': ..., 'LAST_NAME':
...}, {'FIRST_NAME': ..., 'LAST_NAME': ...}]` (which will give you a list that
has equal length as `test_df`). This might be one possibility to easily map it
to a correct row.

