Reputation: 1460
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
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