-1

I am trying to convert the following o/p of my SQL query (as a dataframe) to a dictionary of list:

Column A   Column B
M             N
M             O

I want the result in following format:

{M:[N,O]}

Can someone help me in this?

loyala
  • 175
  • 2
  • 13

2 Answers2

2

You could try like this:

a_dict = df.groupby('Column A', as_index=True)['Column B'].apply(list).to_dict()

print(a_dict)
{'M': ['N', 'O']}
ouroboros1
  • 9,113
  • 3
  • 7
  • 26
  • This answer gets you going - SQL result / csv - all the same ? https://stackoverflow.com/questions/25055958/group-data-from-a-csv-file-by-field-value – irnerd Aug 01 '22 at 16:30
  • This solution is better because it doesn't require you to create lists. – Epic_Yarin_God Aug 01 '22 at 16:50
1

This worked for me:

   tst = data.groupby("a", as_index =False).agg("|".join)
    tst['b'] = tst['b'].apply(lambda x: x.split("|"))
    a, b = tst['a'].tolist(), tst['b'].tolist()
    your_dict = dict(zip(a,b))

and vola

Please note that this is a round about way, and there is probably a better solution.

Epic_Yarin_God
  • 107
  • 1
  • 9