pylearner
pylearner

Reputation: 1460

create a dictionary out of two columns with a unique key and list of values

Am trying to create a dictionary with a unique key and multiple values

Df :

key value
2   21
2   32
2   455
3   12
3   45
3   21

Expected output:

{'2' : ['21', '32', '455'], '3': ['12','45','21']}

code :

dict(zip(df['key'], df['value']))

need some help

Upvotes: 6

Views: 2430

Answers (1)

jezrael
jezrael

Reputation: 862511

First aggregate list by GroupBy.agg and then convert Series to dictionary by Series.to_dict:

d = df.groupby('key')['value'].agg(list).to_dict()
print (d)
{2: [21, 32, 455], 3: [12, 45, 21]}

Upvotes: 9

Related Questions