Home > Software engineering >  df.to_dict make duplicated index (pandas) as primary key in a nested dict
df.to_dict make duplicated index (pandas) as primary key in a nested dict

Time:02-13

I have this data frame which I'd like to convert to a dict in python, I have many other categories, but showed just two for simplicity

Category   Name                     Description             Price       
Diesel     Land Rover               No Description found    £ x
Electric   Tesla Model X            No Description found    £ x

I want the output to be like this

dict = {"Category": {"Diesel" : {
                                "Name": "Land Rover", 
                                "Description":"No Description Found", 
                                "Price": "£ x" },
                                           
                    "Electric" : {"Name": "Tesla Model X", 
                                  "Description":"No Description Found", 
                                  "Price": "£ x" }
                    }               
        }

CodePudding user response:

You can start by creating a dictionary for each record and then group by category to create the final dictionary format desired.

df['dict'] = df[['Name', 'Description', 'Price']].to_dict("records")

dictionary = dict()
dictionary['Category'] = df.groupby('Category')['dict'].apply(list).to_dict()
  • Related