SuperSaiyan
SuperSaiyan

Reputation: 25

Need help creating a dictionary with duplicate keys

I tried creating a list from dataframe columns then create a dictionary from it. However, I couldn't produce a desired output because there are multiple keys(dataframe.index, dataframe.somecolumn).

I tried:


sample df: 
index sender
0      Julia
0      Alfred
0      Nana
1      Kaja
1      Lunox
1      December

dict(zip(df.index, df.sender))

but it only retains the first value on the sender column.

desired output:
{0: [Julia, Alfred, Nana], 1: [Kaja, Lunox, December]}

Upvotes: 1

Views: 595

Answers (1)

yatu
yatu

Reputation: 88275

As mentioned in the comments dictionaries cannot have duplicate keys. One approach could be to groupby the index, aggregate with the list constructor and use the .to_dict() method:

df.groupby('index').sender.apply(list).to_dict()
# {0: ['Julia', 'Alfred', 'Nana'], 1: ['Kaja', 'Lunox', 'December']}

Upvotes: 1

Related Questions