Create dictionary from dataframe using multiple columns

Viewed 182

I need to create a dictionary where each element is a row. The key represents a specific column and the values will be a list of the remaining column entries. Simple example below:

example df:

Col_A     Col_B    Col_C    Col_D
Roger      5        blue    house
Kim        2        green   car
Mike       10       red     bike

desired dictionary = {'Roger':['5','blue','house'],'Kim':['2','green','car'],'Mike':['10','red','bike']}

Any suggestions are appreciated!

2 Answers

Set the index to COl_A then transpose the frame and convert to dictionary with orientation set to list

df.set_index('Col_A').T.to_dict('list')

{'Roger': [5, 'blue', 'house'],
 'Kim': [2, 'green', 'car'],
 'Mike': [10, 'red', 'bike']}

Try:

print(df.set_index("Col_A").apply(list, 1).to_dict())

Prints:

{'Roger': [5, 'blue', 'house'], 'Kim': [2, 'green', 'car'], 'Mike': [10, 'red', 'bike']}
Related