Tarun Tarun - 2 months ago 14
Python Question

Creating dictionary from dataframe in python

I want to create a dictionary out of my data frame. Data frame look like this:

Vehical | Brand | Model Name
car | Suzuki | abc
car | Honda | def
bike | Suzuki | xyz
bike | Honda | asd


I want my dictionary like:

{car : {Suzuki : abc, Honda : def}, bike : {Suzuki : xyz, Honda : asd}}

Answer

you can do it this way:

In [29]: df.pivot(index='Vehical', columns='Brand', values='Model Name').to_dict('i')
Out[29]:
{'bike': {'Honda': 'asd', 'Suzuki': 'xyz'},
 'car': {'Honda': 'def', 'Suzuki': 'abc'}}

result of pivoting:

In [28]: df.pivot(index='Vehical', columns='Brand', values='Model Name')
Out[28]:
Brand   Honda Suzuki
Vehical
bike      asd    xyz
car       def    abc
Comments