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

Viewed 1365

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

1 Answers

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]}
Related