I wish to convert the below dataframe to a nested dictionary
df_2 = pd.DataFrame([{
'id': "qt1",
'email': '[email protected]',
'company_name': "11-50",
'first_name': "aram",
'last_name': "lord",
'title': "ceo"},
{'id': "qt2",
'email': '[email protected]',
'company_name': "unke3",
'first_name': "mich",
'last_name': "smith",
'title': "vp"},
{ 'id': "qt3",
'email': '[email protected]',
'company_name': "triop",
'first_name': "sela",
'last_name': "augus",
'title': "cfo"}])
that looks like this
{'enrichments': [
{'id': 'qt1', 'email': '[email protected]', 'company_name': 'Apple', 'first_name': 'aram', 'last_name': 'lord', 'title': 'ceo',},
{'id': 'qt2','email': '[email protected]', 'company_name': 'unke3', 'first_name': 'mich', 'last_name': 'smith', 'title': 'vp',},
{'id': 'qt3','email': '[email protected]', 'company_name': 'triop', 'first_name': 'sela', 'last_name': 'augus', 'title': 'cfo',}
],}
I tried using groupby and to_dict, but it did not work. Any suggestions? Thanks up front for the help.
CodePudding user response:
You can use to_dict
with a different orientation:
new_dict = {'enrichments': df_2.to_dict(orient='records')}
gives:
{'enrichments': [{'id': 'qt1', 'email': '[email protected]', 'company_name': '11-50', 'first_name': 'aram', 'last_name': 'lord', 'title': 'ceo'},
{'id': 'qt2', 'email': '[email protected]', 'company_name': 'unke3', 'first_name': 'mich', 'last_name': 'smith', 'title': 'vp'},
{'id': 'qt3', 'email': '[email protected]', 'company_name': 'triop', 'first_name': 'sela', 'last_name': 'augus', 'title': 'cfo'}]}