What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Convert Pandas Series to Dict in Python (with code)

  • Jun 10, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Riddhima Agarwal
Convert Pandas Series to Dict in Python (with code)

Python contains a large of number libraries, that make highly complicated tasks very easy to achieve. Pandas is one such library and is used for data manipulation and analysis. To be specific, It includes operations for manipulating numerical tables and time series. In this article, we will learn how to convert a Pandas series to a dictionary in Python.

But before going straight to the methods, let us have a quick recap of the series and dictionary data structure.

What is Pandas Series?

Pandas Series is essentially a one-dimensional labeled data structure that is available only in the Pandas library. It can store all types of data such as strings, integers, floats, and other Python objects. Each element in this data structure has a label associated with it, and all the labels collectively are referred to as an index. 

Also, learn exciting Pandas exercises for beginners if you truly want to master them.

What is a Dictionary in Python?

A dictionary is a data structure in Python, which stores information in the form of key-value pairs. It is written in curly braces consisting of keys and values. When the key is known, dictionaries are optimized to retrieve values. Note that duplicate keys are allowed in a dictionary.

Convert Pandas Series to Dictionary in Python

Dictionaries allow us to quickly find values if the keys are known. If we have a pandas Series with some relevant index, then we can convert it to a dictionary object containing “index: value” key-value pairs to effectively find values by using the corresponding index.

 We can convert Pandas series to Dictionary in Python by using a method called Series.to_dict(). This method is an inbuilt method present in the Series class of the Pandas module. 

The method syntax is as follows:

Series.to_dict(into=<class 'dict'>)

 

This method takes the Series object which we want to convert as its argument and returns the Key-value representation of the passed Series. Let us now look at a few examples to see this function in action. For example:

# importing pandas as pd
import pandas as pd

# Creating the Series using default index
sr1 = pd.Series(['Apple', 'Orange', 'Banana', 'Grapes', 'Brinjal'])

# Creating the Series using custom index
index = ["Red", "Orange", "Yellow", "Green", "Purple"] 
sr2 = pd.Series(['Apple', 'Orange', 'Banana', 'Grapes', 'Brinjal'], index = index)

# Convert to dictionary
dict1 = sr1.to_dict()
dict2 = sr2.to_dict()

print("Series with default indexes")
print(dict1)
print("Series with custom indexes")
print(dict2)

 

Output:

Series with default indexes
{0: 'Apple', 1: 'Orange', 2: 'Banana', 3: 'Grapes', 4: 'Brinjal'}
Series with custom indexes
{'Red': 'Apple', 'Orange': 'Orange', 'Yellow': 'Banana', 'Green': 'Grapes', 'Purple': 'Brinjal'}

 

Pandas Series to dict with a column as key

In many circumstances, converting a series into a dictionary with a column as the key can be helpful. It can be used, for instance, to transfer data across modules of a Python program or to arrange data so that it is simple to enter into a database.

A Pandas Series can be turned into a dictionary with a column as the key using the to_dict() method. It produces a dictionary with the corresponding elements belonging to the Pandas Series as keys and the index labels of the Pandas Series as values. 

Here is an example:

import pandas as pd

# create a Pandas Series
s = pd.Series([1, 2, 3], index=['a', 'b', 'c'])

# convert the Pandas Series to a dictionary with column as key
d = s.to_dict()

# print the dictionary
print(d)

 

Output:

{'a': 1, 'b': 2, 'c': 3}

 

The first step in this example is to build a Pandas Series containing three items and the names "a," "b," and "c." After that, the Pandas Series is transformed into a dictionary using the to_dict() method. As you can see, the generated dictionary uses the same keys as the Pandas Series' first publication. The Pandas Series values are those of the dictionary.

 

Pandas Series to dict without Index

Using dictionary comprehension is one technique to turn a Pandas Series into a dictionary without index labels. By iterating over the items of the Series and constructing a key-value combination for each element, dictionary comprehension is a condensed way to create a dictionary that can be utilised for generating a dictionary from a Pandas Series.

Here is an example:

import pandas as pd

# create a Pandas Series
s = pd.Series([1, 2, 3], index=['a', 'b', 'c'])

# convert the Pandas Series to a dictionary without index
d = {key: value for key, value in s.items()}

# print the dictionary
print(d)

 

Output:

{'a': 1, 'b': 2, 'c': 3}

 

The first step in this example is to construct a Pandas Series with three items and the matching labels "a," "b,". Learn more about Dictionary comprehension in Python to truly understand how it works..

Conclusion

A good programmer knows his or her way around conversions between different types of objects. In this article, we learned how to convert from pandas series to dict in Python. If you are planning to work in the Data Science or Machine Learning domain then we strongly recommend you to have a hold on such types of conversions.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Riddhima Agarwal
Hey, I am Riddhima Agarwal, a B.tech computer science student and a part-time technical content writer. I have a passion for technology, but more importantly, I love learning. Looking forward to greater opportunities in life. Through my content, I want to enrich curious minds and help them through their coding journey