I have a dataframe
df =
name age character
0 A 10 fire
1 A 15 water
2 A 20 earth
3 A 25 air
4 B 10 fire
5 B 7 air
I want to convert this dataframe to dictionary, so that output will be,
dic = {'A': [[10, 15, 20, 25], ['fire', 'water', 'earth', 'air']],
'B': [[10, 7], ['fire', 'air']] }
What I tried is,
from collections import defaultdict
dic = defaultdict(list)
for i in range(len(df)):
dic[df.loc['name', i]].append(df.loc['age', i])
dic[df.loc['name', i]].append(df.loc['character', i]) # this is wrong. It appends to existing list.
If I declare dic = defaultdict([[], []])
, it throws error that first argument of defaultdict must be callable or None.
How can I improve this dictionary?