Pandas Series.to_dict()


Pandas Series.to_dict() Tutorial

In this tutorial, we'll explore the Series.to_dict() method in Pandas, which is used to convert a Pandas Series into a Python dictionary, with well detailed examples.

The syntax of Series.to_dict() is simple, as it doesn't require any parameters:

Series.to_dict()

The Series.to_dict() method returns a dictionary where the keys are the indices of the Series, and the values are the corresponding elements of the Series.


Examples for Series.to_dict()

1. Convert Series to a Dictionary

In this example, we'll take a series in use Series.to_dict() to convert a Pandas Series into a Python dictionary.

Python Program

import pandas as pd

# Create a Series
series = pd.Series({'Name': 'Alice', 'Age': 25, 'City': 'New York'})

# Convert the Series to a dictionary
result_dict = series.to_dict()

# Print the original Series and the resulting dictionary
print("Original Series:")
print(series)
print("\nResulting Dictionary:")
print(result_dict)

Output

Original Series:
Name       Alice
Age           25
City    New York
dtype: object

Resulting Dictionary:
{'Name': 'Alice', 'Age': 25, 'City': 'New York'}

2. Convert Series to a Dictionary with Custom Index

In this example, we'll create a Series with custom indices and then use Series.to_dict() to convert it into a dictionary.

Python Program

import pandas as pd

# Create a Series with custom indices
custom_indices = ['Person', 'Years', 'Location']
series = pd.Series(['Alice', 25, 'New York'], index=custom_indices)

# Convert the Series to a dictionary
result_dict = series.to_dict()

# Print the original Series and the resulting dictionary
print("Original Series:")
print(series)
print("\nResulting Dictionary:")
print(result_dict)

Output

Original Series:
Person         Alice
Years             25
Location    New York
dtype: object

Resulting Dictionary:
{'Person': 'Alice', 'Years': 25, 'Location': 'New York'}

Summary

In this tutorial, we've covered the Series.to_dict() method in Pandas, which provides a convenient way to convert the elements of a Pandas Series into a Python dictionary.


Python Libraries