Converting Dataframe to required list of dictionaries

alokeranjan
my DataFrame is:
Stock Name High Low Range
0 BANDHANBNK 484.9 475.15 9.75
1 COLPAL 1518.6 1506.90 11.70
2 MCDOWELL-N 585.9 579.55 6.35
i Want to convert it as list of dictionaries as following:
list:[{'Stock Name': 'BANDHANBNK', 'High': 484.9, 'Low': 475.15, 'Range': 9.75},{'Stock Name': 'COLPAL', 'High': 1518.6, 'Low': 1506.9, 'Range': 11.69},{'Stock Name': 'MCDOWELL-N', 'High': 585.9, 'Low': 579.55, 'Range': 6.35}]

I run the code:
import pandas as pd
import pdb
df =pd.read_excel("my excel.xlsx")
row_num=df.shape[0]
col_num=df.shape[1]
my_list=[]
my_dict={}
j=0
while j<row_num:
for i in range(0, col_num):
my_dict[df.columns[i]]=df.iloc[j,i]
my_list.append(my_dict)
j=j+1
print(my_list)

buy final output is coming:
[{'Stock Name': 'MCDOWELL-N', 'High': 585.9, 'Low': 579.55, 'Range': 6.35}, {'Stock Name': 'MCDOWELL-N', 'High': 585.9, 'Low': 579.55, 'Range': 6.35}, {'Stock Name': 'MCDOWELL-N', 'High': 585.9, 'Low': 579.55, 'Range': 6.35}]

can anyone help what could be the reason for it.
  • tahseen
    @alokeranjan What is the difference ? Or are you wanting key with value as list

    then you should do in the last line as

    my_json = {'list' : my_list}
    print(my_json)
Sign In or Register to comment.