-1

Say that I have a data frame df that looks like the following:

    A     B
0  key1   value1
1  key2   value2
2  key2   value3
3  key3   value4
4  key3   value5

How can I transform it into a dictionary dic that looks like this in the most time efficient way:

{key1: [value1], 
key2: [value2, value3], 
key3: [value4, value5]}
Kaihua Hou
  • 310
  • 1
  • 2
  • 11

1 Answers1

1

You could use groupby + agg(list) + to_dict:

out = df.groupby('A')['B'].agg(list).to_dict()

Output:

{'key1': ['value1'],
 'key2': ['value2', 'value3'],
 'key3': ['value4', 'value5']}