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
JavaScript
x
4
1
Category Name Description Price
2
Diesel Land Rover No Description found £ x
3
Electric Tesla Model X No Description found £ x
4
I want the output to be like this
JavaScript
1
11
11
1
dict = {"Category": {"Diesel" : {
2
"Name": "Land Rover",
3
"Description":"No Description Found",
4
"Price": "£ x" },
5
6
"Electric" : {"Name": "Tesla Model X",
7
"Description":"No Description Found",
8
"Price": "£ x" }
9
}
10
}
11
Advertisement
Answer
You can do this without assigning an additional column or aggregating using list
:
JavaScript
1
5
1
def collect(category):
2
return category[['Name', 'Description', 'Price']].to_dict('records')
3
4
data = {'Category': df.groupby('Category').apply(collect).to_dict()}
5
I created a separate function for readability – you could, of course, pass it as a lambda too:
JavaScript
1
5
1
{
2
'Category': df.groupby('Category').apply(
3
lambda x: x[['Name', 'Description', 'Price']].to_dict('records')).to_dict()
4
}
5