You have a pandas dataframe and you want to convert it to a python dictionary.

Solution –
To convert a pandas dataframe into a python dictionary, we use the pd.DataFrame.to_dict() method.
# import pandas
import pandas as pd
# read the csv file in pandas
df = pd.read_csv('../data/Restaurant.csv')
# convert df to dict
df.to_dict()

The df.to_dict() method also has a orient parameter that let’s you decide how you want to do the orientation of the dictionary. By Default it is – ‘dict’ (default) : dict like {column -> {index -> value}}
If you want you can change this orientation to a list like this – ‘list’ : dict like {column -> [values]}
df.to_dict(orient='list')

You can find other options for the orientation here – pandas to_dict
Related Posts –
- Create Pandas DataFrame from Lists and List of Lists.
- Create Pandas DataFrame from dictionary.
- Create a Pandas Series from a list.
2 thoughts