2

I have a dataframe like:

subject   score_A   score_B   score_C
math        90        75        50
art         85        65        45
econ        90        80        60

I want to make them into a dict like:

{
   'math':{'A': 90,
           'B': 75,
           'C': 50},
   'art': {'A': 85,
           'B': 65,
           'C': 45},
   'econ':{'A': 90,
           'B': 80,
           'C': 60},
}

The actual dataframe is much longer and a bit wider (with more keys for each subject than A, B, and C).

I suppose this has something to do with generating list of lower-level keys like A, B, C, etc and using the zip function but none of my limited tries worked.

Grumpy Civet
  • 375
  • 1
  • 7

4 Answers4

2

You can set subject as index and then use to_dict with orient param -

df.set_index('subject').to_dict(orient='index')
Tom Ron
  • 5,906
  • 3
  • 22
  • 38
  • Thanks Tom! This is so convenient. But I still wonder if we could achieve this by using something like ```dict(zip(.....))``` (if it's possible and not too complicated) – Grumpy Civet Mar 30 '22 at 08:03
2

You can first generate a list of dictionaries and then use zip to construct the final dictionary.

dict(zip(df["subject"], [dict(df.iloc[i, 1:]) for i in range(len(df))]))

Of course a bit ugly to loop over the dataframe.

Jim Ögren
  • 31
  • 2
1

I guess you can use to_dict(). you can find the answer in the below link

Convert a Pandas DataFrame to a dictionary

TariqShah
  • 25
  • 7
1

Use set_index and transpose before converting the DataFrame to_dict

df.set_index("subject").T.to_dict()