The to_dict()
method in Pandas is used to convert a DataFrame into a dictionary.
Example
import pandas as pd
# sample DataFrame
data = {'A': [1, 2, 3],
'B': [4, 5, 6]}
df = pd.DataFrame(data)
# convert the DataFrame to a dictionary
data_dict = df.to_dict()
print(data_dict)
'''
Output
{'A': {0: 1, 1: 2, 2: 3}, 'B': {0: 4, 1: 5, 2: 6}}
'''
to_dict() Syntax
The syntax of the to_dict()
method in Pandas is:
df.to_dict(orient='dict')
to_dict() Argument
The to_dict()
method takes the following argument:
orient
(optional): defines the format of the resulting dictionary
to_dict() Return Value
The to_dict()
method returns a dictionary representation of the DataFrame. The structure of the returned dictionary depends on the orient
parameter.
Example 1: Default Orientation
import pandas as pd
data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)
# default to_dict() usage
dict_data = df.to_dict()
print(dict_data)
Output
{'A': {0: 1, 1: 2, 2: 3}, 'B': {0: 4, 1: 5, 2: 6}}
Here, we converted a DataFrame to a dictionary with the default dict
orientation, where each column became a key in the dictionary.
Example 2: 'list' Orientation
import pandas as pd
data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)
# convert DataFrame to dictionary with 'list' orientation
list_data = df.to_dict('list')
print(list_data)
Output
{'A': [1, 2, 3], 'B': [4, 5, 6]}
In this example, we converted a DataFrame to a dictionary where each column is represented as a list of values.
Example 3: 'records' Orientation
import pandas as pd
data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)
# convert DataFrame to dictionary with 'records' orientation
records_data = df.to_dict('records')
print(records_data)
Output
[{'A': 1, 'B': 4}, {'A': 2, 'B': 5}, {'A': 3, 'B': 6}]
Here, we converted a DataFrame to a list of dictionaries, with each dictionary representing a row in the DataFrame.
Example 4: 'index' Orientation
import pandas as pd
data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)
# convert DataFrame to dictionary with 'index' orientation
index_data = df.to_dict('index')
print(index_data)
Output
{0: {'A': 1, 'B': 4}, 1: {'A': 2, 'B': 5}, 2: {'A': 3, 'B': 6}}
In this example, we converted a DataFrame to a dictionary where the keys are the DataFrame index and the values are dictionaries of column:data
pairs.
Note: In the examples above, it's assumed that the DataFrame's index is the default Pandas index. If your DataFrame has a different index, the output of the to_dict()
method will reflect that index instead.