0

I have a dataframe like the following:

        Keyword    Value
   0         K1       V1
   1         K2       V2
   2         K3       V3

And I would like to return a json like so:

{
    "K1":"V1",
    "K2":"V2",
    "K3":"V3"
}

My approach right now is to basically convert to dictionary first with df.to_dict(orient='list'), extract the Keyword and Value lists, go through the lists and create a separate dictionary, then convert to json. I would like to know if there is a more elegant and direct way to do this from the dataframe itself. Thanks.

Isaac
  • 204
  • 2
  • 10

2 Answers2

3

Try:

df.set_index('Keyword')['Value'].to_dict()

or

dict(zip(df['Keyword'], df['Value']) )
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
1

Use:

In [661]: df.set_index('Keyword')['Value'].to_dict()
Out[661]: {'K1': 'V1', 'K2': 'V2', 'K3': 'V3'}
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58