Home > OS >  Trying to convert a dataframe to a dictionary in Python-Pandas
Trying to convert a dataframe to a dictionary in Python-Pandas

Time:11-25

I've got the following dataframe

      Firm      Item  Cost
0   Firm A     Books  0.55
1   Firm A   Pencils  0.60
2   Firm B     Books  0.45
3   Firm B   Pencils  0.35

and I would like to convert it into the following dictionary

{('Firm A', 'Books'): 0.55, ('Firm A', 'Pencils'): 0.6, ('Firm B', 'Books'): 0.45, ('Firm B', 'Pencils'): 0.35}

I tried with

costs_dictionary = df.set_index('Firm','Item').to_dict()

But with no success.

CodePudding user response:

Add list to DataFrame.set_index and select column Cost before to_dict:

costs_dictionary = df.set_index(['Firm','Item'])['Cost'].to_dict()
print (costs_dictionary)
{('Firm A', 'Books'): 0.55, ('Firm A', 'Pencils'): 0.6, 
 ('Firm B', 'Books'): 0.45, ('Firm B', 'Pencils'): 0.35}
  • Related