python - dataframe columns into dict of dicts

Viewed 56

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.

4 Answers

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

df.set_index('subject').to_dict(orient='index')

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.

Related