Grumpy Civet
Grumpy Civet

Reputation: 381

python - dataframe columns into dict of dicts

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.

Upvotes: 2

Views: 74

Answers (4)

Athibet Prawane
Athibet Prawane

Reputation: 91

Use set_index and transpose before converting the DataFrame to_dict

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

Upvotes: 1

Jim Ögren
Jim Ögren

Reputation: 31

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.

Upvotes: 2

TariqShah
TariqShah

Reputation: 25

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

Convert a Pandas DataFrame to a dictionary

Upvotes: 1

Tom Ron
Tom Ron

Reputation: 6181

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

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

Upvotes: 2

Related Questions