Reputation: 195
I have an Excel file with a structure like this
name age status
anna 35 single
petr 27 married
Is there any generic way to convert such an Excel file into a nested dictionary with a structure like this
{'anna': {'age':35}, {'status': 'single'}},
{'petr': {'age':27}, {'status': 'married'}}
Should I first import an excel file and convert it into pandas dataframe and then to create a nested dictionary or does it exist a straight way of importing an excel sheet and creating such a dictionary?
Upvotes: 0
Views: 2944
Reputation: 81594
The output you are asking for isn't a valid Python data strcture.
You can achieve something similar with df.to_dict:
import pandas as pd
df = pd.read_excel('path/to/file')
df.set_index('name', inplace=True)
print(df.to_dict(orient='index'))
# {'petr': {'age': 27, 'status': 'married'}, 'anna': {'age': 35, 'status': 'single'}}
Upvotes: 1