Convert data to dictionary

I intend to get the dictionary with the column name as the key from the data frame.

Suppose I have a dataframe:

    a    b
 0  ac   dc
 1  ddd  fdf

I want the result to be as follows:

{a : ac, b : dc}

I want this to be done line by line. Any help would be greatly appreciated. Here I want the column name to be the key in the resulting dictionary.

+4
source share
1 answer

You can use the method to_dict()withorient='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'}]
+7
source

Source: https://habr.com/ru/post/1620496/


All Articles