In this Python tutorial, we will learn how to convert Pandas DataFrame to a Dictionary in Python. Also, we will cover these topics.
- Convert Pandas DataFrame to a Dictionary
- Convert Pandas DataFrame to Dictionary Without Index
- Convert Pandas DataFrame to Dictionary List
- Convert Pandas DataFrame to Nested Dictionary
- Convert Pandas Series to Dictionary
- Convert Pandas Column to Dictionary
- Python Pandas Covert DataFrame to Dictionary with Multiple Values.
- Convert Pandas DataFrame to Dictionary with One Column as Key
- Convert Pandas Row To Dictionary
We have demonstrated examples using the USA House Sale Prediction Dataset available on Kaggle.
Convert Pandas DataFrame to a Dictionary
In this section, we will learn how to convert pandas dataframe to a dictionary in Python.
- DataFrame is the representation of data in tabular form i.e. Rows and Columns.
- Dictionary is the key-value pair. Each key are unique and values can be of any data type.
- Another name for dictionary is dict so if you are looking for how to convert pandas dataframe to a dict. then you can follow the solution presented in this section.
- Using dataframe.to_dict() in Python Pandas we can convert the dataframe to dictionary. 2
- In our example, we have used USA House Sale Prediction dataset that is downloaded from kaggle.
df.head(5).to_dict()
, in this code we have converted only top 5 rows of the dataframe to dictionary.- All the data has been converted to key-value pair and their data type is dictionary now.
Also, Read: Python Pandas Drop Rows
Convert Pandas DataFrame to Dictionary Without Index
In this section, we will learn how to convert pandas dataframe to the dictionary without an index.
- index are the serial number that keeps the record of number of records.
- When we convert dataframe to dictionary using
dataframe.to_dict()
then index is not recorded automatically because orient is set to ‘dict’. - to convert pandas dataframe to dictionary simply write
dataframe.to_dict('index')
. - In our example, we have demonstrated both please refer to the comments in the jupyter notebook.
Read: How to Drop Duplicates using drop_duplicates()
Convert Pandas DataFrame to Dictionary List
In this section, we will learn how to convert the dataframe to a dictionary list in Python Pandas.
- Lists are used to store multiple items inside one variable.
- Using
dataframe.to_dict(orient='list')
we can convert pandas dataframe to dictionary list. - In the below example, all the values are converted into List format whereas column heading are keys. To see the difference please refer to other sections of this tutorial.
Read: Groupby in Python Pandas
Convert Pandas DataFrame to Nested Dictionary
In this section, we will learn how to convert pandas dataframe to a nested dictionary.
- Nested dictionary means dictionary inside the dictionary.
- Using
dataframe.to_dict(orient='dict')
we can create nested dictionary. - In our example we have demonstrated how to convert pandas dataframe to nested dictionary.
Read: Crosstab in Python Pandas
Convert Pandas Series to Dictionary
In this section, we will learn how to convert Pandas Series to Dictionary in Python.
- Pandas Series is one-dimensional array that is capable of holding any data type.
- Dictionaries are key-value pair.
- Since series is one-dimensional array so it do not fulfill the requirement for dictionary but by using series.to_dict() we can convert the series to dictionary.
- This function will use value’s index as the key and will display the value against the key.
Read: Missing Data in Pandas in Python
Convert Pandas Column to Dictionary
In this section, we will learn how to convert Pandas Column to the dictionary. This topic is similar to ‘Convert Pandas DataFrame to Dictionary.’
In this output, we have converted columns of the top 5 rows to a dictionary in Python Pandas.
Read: Python Pandas CSV Tutorial
Python Pandas Covert DataFrame to Dictionary with Multiple Values.
In this section, we will learn how to convert the dataframe to the dictionary with multiple values in Python Pandas.
- Here multiple values means, same value has appeared multiple times and we have to combine it together in such a way that the repeated values become single key and all the responses are packed in a list.
- to explain it better, we have created a table below with fruits and their session.
Fruits | Season |
---|---|
Mango | Summer season |
Apple | Winter Season |
Kiwi | Winter Season |
Dates | Winter Season |
Peach | Rainy Season |
Plum | Summer season |
- In this table, fruits are categorised with their respective season. But you can notice that summer and winter seasons are repeated multiple times.
- So before we convert these values in a dictionary it is import to groupby these seasons.
- Using crossrtab or groupby, we can convert this table into something like this:
- ‘summer season’ : [‘Mango’, ‘Plum’],
- ‘Winter Season’: [‘Apple’, ‘Kiwi’, ‘Dates’],
- ‘Rainy Season:’ [‘Peach’]
- In this way, this looks far better and self explanatory. Same thing we are going to do on our dataset on ‘USA house sale prediction’.
- In the below example, we have cleaned the dataset by removing not required columns.
- Then we have used sample function to pickup 10 random data from the dataset.
- In the end, we have groupby the data with zipcode.
Read Missing Data in Pandas in Python
Convert Pandas DataFrame to Dictionary with One Column as Key
In this section, we will learn how to convert pandas dataframe to dictionary win one column as key in Python.
- If a dataframe has 5 columns then out of them one will become the key.
- This con be done using Transpose
.T.()
function Python Pandas. - In our example, we have selected zipcode as a key.
df.head(5).set_index('zipcode').T.to_dict('list')
- This code is responsible for converting Pandas DataFrame to Dictionart with one columns as key. Here is the description of the code.
df.head(5)
, this code will display top 5 rows of the dataset..set_index('zipcode')
, this part of code sets the zipcode as a index..T.()
, transpose plays an important role here. It helps in exchanging the values. Matrix has rules to perform the operations (addition, multiplication, etc.) Transpose take care of these rules and does the needful adjustments.to_dict()
, In this code, the dataframe is converted to dictionary.
- In the below implementation, you can see that each value is has key as zipcode.
Read Python dictionary of lists
Convert Pandas Row To Dictionary
In this section, we will convert Pandas Row to Dictionary using Python.
- Rows are the horizontal values in the table or dataframe. Each new record creates a new row in a dataset.
- When rows are converted to dictionary then column name becomes the key and value is presented infront of.
- each record is presented in a key-value pair format.
- Using
dataframe.to_dict(orient='records')
, we can convert the pandas Row to Dictionary. - In our example, we have used USA house sale prediction dataset and we have converted only 5 rows to dictionary in Python Pandas.
- You can notice that, key column is converted into a key and each row is presented seperately.
You may like the following Python Pandas tutorials:
- Pandas Delete Column
- Add row to Dataframe Python Pandas
- Convert Integers to Datetime in Pandas
- How to Set Column as Index in Python Pandas
In this tutorial, we have learned how to convert Pandas DataFrame to a Dictionary in Python. Also, we have covered these topics.
- Convert Pandas DataFrame to a Dictionary
- Convert Pandas DataFrame to Dictionary Without Index
- Convert Pandas DataFrame to Dictionary List
- Convert Pandas DataFrame to Nested Dictionary
- Convert Pandas Series to Dictionary
- Convert Pandas Column to Dictionary
- Python Pandas Covert DataFrame to Dictionary with Multiple Values.
- Convert Pandas DataFrame to Dictionary with One Column as Key
- Convert Pandas Row To Dictionary
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.