paDU
paDU

Reputation: 45

Hto convert pandas df into dict based on repeated rows (row has to be key)

I want to ask Hto convert pandas df into dict like I show below: I have df like this:

col1   col2
"a"   12
"a"   2
"b"   34
"c"   9
"c"   45

and I need dict like this:

d = {"a":[12, 2], "b":[34], "c":[9, 45]}

Anyone give me some tips? Kindly help.

Upvotes: 1

Views: 38

Answers (1)

jezrael
jezrael

Reputation: 863166

First aggregate to lists and then convert output to dict:

df.groupby('col1')['col2'].agg(list).to_dict()

Upvotes: 1

Related Questions