I am trying to write below two separate dict values with the same key header to the csv file using python.
{'instrumentType': 'Stock Futures', 'expiryDate': '25-Jan-2023', 'optionType': '-', 'strikePrice': 0, 'identifier': 'FUTSTKTATASTEEL25-01-2023XX0.00', 'openPrice': 119.85, 'highPrice': 120.9, 'lowPrice': 118.3, 'closePrice': 119, 'prevClose': 119.8, 'lastPrice': 119.3, 'change': -0.5, 'pChange': -0.41736227045075125, 'numberOfContractsTraded': 13024, 'totalTurnover': 85557.26}
{'instrumentType': 'Stock Options', 'expiryDate': '25-Jan-2023', 'optionType': 'Call', 'strikePrice': 120, 'identifier': 'OPTSTKTATASTEEL25-01-2023CE120.00', 'openPrice': 4.1, 'highPrice': 4.7, 'lowPrice': 3.25, 'closePrice': 3.5, 'prevClose': 4.1, 'lastPrice': 3.55, 'change': -0.5499999999999998, 'pChange': -13.414634146341461, 'numberOfContractsTraded': 11663, 'totalTurnover': 2501.71}
I tried following the approach, but only one dict is getting stored in csv.
data = pd.DataFrame.from_dict(ce_dt)
data.to_csv('out.csv', index=False)
Appreciate your help!!
CodePudding user response:
You can use pd.DataFrame.from_records
to construct your dataframe:
import pandas as pd
dict1 = {"a": 1, "b": 2}
dict2 = {"a": 3, "b": 4}
df = pd.DataFrame.from_records([dict1, dict2])
# a b
# 0 1 2
# 1 3 4
df.to_csv("out.csv")
CodePudding user response:
Another option is to use standard csv
module:
import csv
lst = [dict1, dict2] # lst is list of dictionaries
with open('data.csv', 'w') as f_out:
writer = csv.DictWriter(f_out, fieldnames=lst[0].keys())
writer.writeheader()
writer.writerows(lst)
Writes data.csv
:
instrumentType,expiryDate,optionType,strikePrice,identifier,openPrice,highPrice,lowPrice,closePrice,prevClose,lastPrice,change,pChange,numberOfContractsTraded,totalTurnover
Stock Futures,25-Jan-2023,-,0,FUTSTKTATASTEEL25-01-2023XX0.00,119.85,120.9,118.3,119,119.8,119.3,-0.5,-0.41736227045075125,13024,85557.26
Stock Options,25-Jan-2023,Call,120,OPTSTKTATASTEEL25-01-2023CE120.00,4.1,4.7,3.25,3.5,4.1,3.55,-0.5499999999999998,-13.414634146341461,11663,2501.71