Home > front end >  Dictionary of dictionaries from data frame
Dictionary of dictionaries from data frame

Time:09-22

I have created a data frame from data got from database. I need to convert the data frame to dictionary with format mentioned below.

{ 0 : {'column1': 'value', 'column2' : 'value',....},
1 : {'column1': 'value', 'column2' : 'value',....},....

I tried

data_list = [tuple(r) for r in data_df.to_numpy().tolist()]#convert df to list of tuples

data_dict = [dict(zip(ag_titles, x)) for x in data_list]
data_final = {i:{k:v for k,v in dict(data_dict).items}for i in range(len(data_dict))}

But I am not getting the expected output. How can this be done with dictionary comprehension?

CodePudding user response:

Try this:

df.to_dict('index')

example:

df = pd.DataFrame({
    'Year': ['a1', 'a2', 'a3', 'a4', 'a5'],
    'Company': ['b1', 'b2', 'b3', 'b4', 'b5'],
    'Number': ['c1', 'c2', 'c3', 'c4', 'c5']})


df.to_dict('index')

Output:

{0: {'Year': 'a1', 'Company': 'b1', 'Number': 'c1'},
 1: {'Year': 'a2', 'Company': 'b2', 'Number': 'c2'},
 2: {'Year': 'a3', 'Company': 'b3', 'Number': 'c3'},
 3: {'Year': 'a4', 'Company': 'b4', 'Number': 'c4'},
 4: {'Year': 'a5', 'Company': 'b5', 'Number': 'c5'}}

CodePudding user response:

You can try-

b = data_df.to_dict(orient='index')
  • Related