5

I intend to get a dictionary with column name as key from a dataframe.

Suppose I have a dataframe:

    a    b
 0  ac   dc
 1  ddd  fdf

I want the output as:

{a : ac, b : dc}

I want it to be done row by row. Any sort of help would be greatly appreciated. Here I want the column name as the key in the resulting dictionary.

Sunil Kumar
  • 117
  • 1
  • 2
  • 10

1 Answers1

9

You can use the to_dict() method with orient='records'

import pandas as pd

df = pd.DataFrame([{'a': 'ac', 'b': 'dc'}, {'a': 'ddd', 'b': 'fdf'}])
print(df)

#      a    b
# 0   ac   dc
# 1  ddd  fdf

d = df.to_dict(orient='records')
print(d)

# [{'b': 'dc', 'a': 'ac'}, {'b': 'fdf', 'a': 'ddd'}]
mirosval
  • 6,671
  • 3
  • 32
  • 46