How to Create a Dictionary From a Grouped Dataframe in Python

To create a dictionary from a grouped dataframe in Python, you can use the groupby() function along with the apply() function.

The following example shows how to create a dictionary from a grouped dataframe in Python.

Using groupby() & apply() Function

We can use the groupby() and apply() functions to create a dictionary from a grouped dataframe.

Suppose we have the following dataframe:

# Import pandas library
import pandas as pd

# Create dataframe
df = pd.DataFrame({
    "Product_Name": ["Laptop", "Mobile", "Printer", "Keyboard", "Scanner", "Mouse", "Laptop", "Printer", "Keyboard", "Mouse"],
    "Price": [4500, 550, 250, 50, 350, 50, 3000, 300, 100, 60]
})

# Create grouped dataframe
grouped_df = df.groupby('Product_Name')

# Create dictionary
dictionary = grouped_df.apply(lambda x: x.to_dict('records')).to_dict()

# Show dictionary
print(dictionary)

Output: 👇️

{
    'Keyboard': [{'Product_Name': 'Keyboard', 'Price': 50}, {'Product_Name': 'Keyboard', 'Price': 100}],
    'Laptop': [{'Product_Name': 'Laptop', 'Price': 4500}, {'Product_Name': 'Laptop', 'Price': 3000}],
    'Mobile': [{'Product_Name': 'Mobile', 'Price': 550}],
    'Mouse': [{'Product_Name': 'Mouse', 'Price': 50}, {'Product_Name': 'Mouse', 'Price': 60}],
    'Printer': [{'Product_Name': 'Printer', 'Price': 250}, {'Product_Name': 'Printer', 'Price': 300}],
    'Scanner': [{'Product_Name': 'Scanner', 'Price': 350}]
}

In this example, we use the groupby() function to group the dataframe df by the Product_Name column.

We then use the apply() function to convert each group to a dictionary of records and finally convert the grouped dataframe to a dictionary.

The output shows the dictionary created from the grouped dataframe.

Conclusion

We can use the groupby() and apply() functions to create a dictionary from a grouped dataframe in Python.

This method provides a convenient way to transform grouped data into a dictionary format.