nath
nath

Reputation: 113

How to convert dataframe into dictionary python

I have a dataframe that looks like

Total_Time_words    Words
0      1.50         your
1      2.15         intention
2      2.75         is
3      3.40         dangerous
4      3.85         for

when I use this code:

new.set_index('Words').T.to_dict('records')

I get this output below:

[{'your': 1.5,
  'intention': 2.15,
  'is': 2.75,
  'dangerous': 3.4,
  'for': 3.85,
  'my': 4.0,
  'world': 4.3}]

But this is my expected output below:

[
   {
      1.50:"your"
   },
   
   {
      2.15:"intention"
   }
]

Upvotes: 1

Views: 51

Answers (1)

Sociopath
Sociopath

Reputation: 13401

You can use list comprehension with zip as below:

new_dict = [{k:v} for k,v in zip(df["Total_Time_words"], df["words"])]
print(new_dict)

Upvotes: 1

Related Questions