df.to_dict() can be used to convert a Pandas dataframe to a dictonary. The basic syntax is as follows. Note that,'list'
does not return index
.
df.to_list( orient = ‘list’ )
Sample Data
import pandas as pd
# create a dataframe called df_1
df_1 = pd.DataFrame({'Brand': ['Tesla', 'Toyota','Tesla','Ford'],
'Location': ['CA', 'CA','NY','MA']},index=list('abcd'))
print(df_1)
Brand Location a Tesla CA b Toyota CA c Tesla NY d Ford MA
Method 1: orient='list'
Below is the example of using orient='list'
in to_dict()
.
# using orient='list' in to_dict()
df_1.to_dict(orient='list')
The following is the output. As you can see, there is no index.
{'Brand': {'a': 'Tesla', 'b': 'Toyota', 'c': 'Tesla', 'd': 'Ford'}, 'Location': {'a': 'CA', 'b': 'CA', 'c': 'NY', 'd': 'MA'}}
Method 2: orient='dict'
Below is the example of using orient='dict'
in to_dict()
.
# using orient='dict' in to_dict()
df_1.to_dict(orient='dict')
{'Brand': {'a': 'Tesla', 'b': 'Toyota', 'c': 'Tesla', 'd': 'Ford'}, 'Location': {'a': 'CA', 'b': 'CA', 'c': 'NY', 'd': 'MA'}}
Method 3: orient='series'
Below is the example of using orient='series'
in to_dict()
.
# using orient='series' in to_dict()
df_1.to_dict(orient='series')
{'Brand': a Tesla b Toyota c Tesla d Ford Name: Brand, dtype: object, 'Location': a CA b CA c NY d MA Name: Location, dtype: object}
Method 4: orient='split'
Below is the example of using orient='split'
in to_dict()
. Thus, by using orient='split'
, it creates dictionaries of index, column names, and data.
# using orient='split' in to_dict()
df_1.to_dict(orient='split')
{'index': ['a', 'b', 'c', 'd'], 'columns': ['Brand', 'Location'], 'data': [['Tesla', 'CA'], ['Toyota', 'CA'], ['Tesla', 'NY'], ['Ford', 'MA']]}