I have a dataframe called users_df that looks like this
| id | first_name | last_name | signup_date |
|---|---|---|---|
| 1 | James | Smith | 2021-01-01 |
| 2 | Mark | Adams | 2021-03-02 |
| 3 | Mary | Rose | 2021-05-03 |
users_df = pd.DataFrame([[1, 'James', 'Smith', '2021-01-01'], [2, 'Mark', 'Adams', '2021-03-02'],[3, 'Mary', 'Rose', '2021-05-03']], columns=['id', 'first_name','last_name', 'signup_date'])
Which I am trying to convert into a dictionary first that looks like this:
user_dict = {
"users": [
{"id": 1, "user_fields": {"first_name": "James", "last_name": "Smith", "signup_date": "2021-01-01"}},
{"id": 2, "user_fields": {"first_name": "Mark", "last_name": "Adams", "signup_date": "2021-03-02"}},
{"id": 3, "user_fields": {"first_name": "Mary", "last_name": "Rose", "signup_date": "2021-05-03"}}
]
}
And then finally convert that into a string:
user_dict_string = '{"users": [{"id": 1, "user_fields": {"first_name": "James", "last_name": "Smith", "signup_date": "2021-01-01"}}, {"id": 2, "user_fields": {"first_name": "Mark", "last_name": "Adams", "signup_date": "2021-03-02"}}, {"id": 3, "user_fields": {"first_name": "Mary", "last_name": "Rose", "signup_date": "2021-05-03"}}]}'
The part where I am stuck is converting the dataframe into the dictionary while keeping the "id" part (see the example below when I do to_dict('index')) and then adding the "users" list and the nested "user_fields" parts.
All I could find is using this:
user_dict = user_list.to_dict('index')
But the results look like this which is not what I am after
{1: {'first_name': 'James', 'last_name': 'Smith', 'signup_date': '2021-01-01'}, 2: {'first_name': 'Mark', 'last_name': 'Adams', 'signup_date': '2021-03-02'}, 3: {'first_name': 'Mary', 'last_name': 'Rose', 'signup_date': '2021-05-03'}}
Any help is appreciated