How To Convert Pandas Dataframe To Nested Dictionary Last Updated : 08 Feb, 2024 Comments Improve Suggest changes Like Article Like Report In this article, we will learn how to convert Pandas DataFrame to Nested Dictionary. Convert Pandas Dataframe To Nested DictionaryConverting a Pandas DataFrame to a nested dictionary involves organizing the data in a hierarchical structure based on specific columns. In Python's Pandas library, we can utilize the groupby function along with apply to create groupings based on chosen columns. Let's create a DataFrame that contains information about different products, including their names, prices, and stock quantities. The to_dict method with the parameter orient=records is commonly employed to convert each group into a dictionary of records. Let's see how to convert dataframe to nested dictionary: Using to_dict Python3 import pandas as pd # Your DataFrame data = {'Name': ['Emily', 'David', 'Emily', 'David'], 'Chain': ['Panera Bread', 'Starbucks', 'Subway', 'Chick-fil-A'], 'Food': ['soup', 'coffee', 'sandwich', 'grilled chicken'], 'Healthy': [True, False, True, True]} df = pd.DataFrame(data) # Convert DataFrame to nested dictionary nested_dict = df.groupby('Name').apply(lambda x: x[['Chain', 'Food', 'Healthy']].to_dict(orient='records')).to_dict() print(nested_dict) Output: {'David': [{'Chain': 'Starbucks', 'Food': 'coffee', 'Healthy': False}, {'Chain': 'Chick-fil-A', 'Food': 'grilled chicken', 'Healthy': True}], 'Emily': [{'Chain': 'Panera Bread', 'Food': 'soup', 'Healthy': True}, {'Chain': 'Subway', 'Food': 'sandwich', 'Healthy': True}]}Let's see another complex example, to gain in-depth understanding. Python3 import pandas as pd data = {'Person': ['Alice', 'Bob', 'Alice', 'Bob'], 'Location': ['Home', 'Work', 'Home', 'Work'], 'Activity': ['Cooking', 'Meeting', 'Reading', 'Working'], 'Duration': [30, 60, 45, 120]} df = pd.DataFrame(data) nested_dict_another = df.groupby(['Person', 'Location']).apply(lambda x: x[['Activity', 'Duration']].to_dict(orient='records')).to_dict() print(nested_dict_another) Output: {('Alice', 'Home'): [{'Activity': 'Cooking', 'Duration': 30}, {'Activity': 'Reading', 'Duration': 45}], ('Bob', 'Work'): [{'Activity': 'Meeting', 'Duration': 60}, {'Activity': 'Working', 'Duration': 120}]}ConclusionHence, we can convert Pandas Dataframe To Nested Dictionary with just few lines of code. Comment More infoAdvertise with us Next Article How To Convert Pandas Dataframe To Nested Dictionary jaintarun Follow Improve Article Tags : Pandas Similar Reads How to convert Dictionary to Pandas Dataframe? Converting a dictionary into a Pandas DataFrame is simple and effective. You can easily convert a dictionary with key-value pairs into a tabular format for easy data analysis. Lets see how we can do it using various methods in Pandas.1. Using the Pandas ConstructorWe can convert a dictionary into Da 2 min read Python - Convert dict of list to Pandas dataframe In this article, we will discuss how to convert a dictionary of lists to a pandas dataframe. Method 1: Using DataFrame.from_dict() We will use the from_dict method. This method will construct DataFrame from dict of array-like or dicts. Syntax: pandas.DataFrame.from_dict(dictionary) where dictionary 2 min read Convert PySpark DataFrame to Dictionary in Python In this article, we are going to see how to convert the PySpark data frame to the dictionary, where keys are column names and values are column values. Before starting, we will create a sample Dataframe: Python3 # Importing necessary libraries from pyspark.sql import SparkSession # Create a spark se 3 min read How to create Pandas DataFrame from nested XML? In this article, we will learn how to create Pandas DataFrame from nested XML. We will use the xml.etree.ElementTree module, which is a built-in module in Python for parsing or reading information from the XML file. The ElementTree represents the XML document as a tree and the Element represents onl 3 min read How to convert list of dictionaries into Pyspark DataFrame ? In this article, we are going to discuss the creation of the Pyspark dataframe from the list of dictionaries. We are going to create a dataframe in PySpark using a list of dictionaries with the help createDataFrame() method. The data attribute takes the list of dictionaries and columns attribute tak 2 min read Converting nested JSON structures to Pandas DataFrames In this article, we are going to see how to convert nested JSON structures to Pandas DataFrames. JSON with multiple levels In this case, the nested JSON data contains another JSON object as the value for some of its attributes. This makes the data multi-level and we need to flatten it as per the pro 3 min read How to Convert Pandas DataFrame into a List? In this article, we will explore the process of converting a Pandas DataFrame into a List, We'll delve into the methods and techniques involved in this conversion, shedding light on the versatility and capabilities of Pandas for handling data structures in Python.Ways to convert Pandas DataFrame Int 7 min read Create PySpark dataframe from nested dictionary In this article, we are going to discuss the creation of Pyspark dataframe from the nested dictionary. We will use the createDataFrame() method from pyspark for creating DataFrame. For this, we will use a list of nested dictionary and extract the pair as a key and value. Select the key, value pairs 2 min read How to Convert Index to Column in Pandas Dataframe? Pandas is a powerful tool which is used for data analysis and is built on top of the python library. The Pandas library enables users to create and manipulate dataframes (Tables of data) and time series effectively and efficiently. These dataframes can be used for training and testing machine learni 2 min read 3 Level Nested Dictionary To Multiindex Pandas Dataframe Pandas is a powerful data manipulation and analysis library for Python. One of its key features is the ability to handle hierarchical indexing, also known as MultiIndexing. This allows you to work with more complex, multi-dimensional data in a structured way. In this article, we will explore how to 3 min read Like