简体   繁体   English

在 python 中写入多个字典到 csv

[英]write multiple dict to csv in python

I am trying to write below two separate dict values with the same key header to the csv file using python.我正在尝试使用 python 将具有相同键 header 的两个单独的字典值写入 csv 文件。

{'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.我尝试按照这种方法进行操作,但只有一个字典存储在 csv 中。

data = pd.DataFrame.from_dict(ce_dt)
data.to_csv('out.csv', index=False)

Appreciate your help!!感谢你的帮助!!

EDIT编辑

The data is stored in a variable as follows:数据存储在变量中,如下所示:

在此处输入图像描述

There is no comma , between the dict and that's why it is getting written only one dict.字典之间没有逗号这就是为什么它只写一个字典的原因。

Sample:样本:

{'underlying': 'MARUTI', 'identifier': 'OPTSTKMARUTI25-01-2023CE8500.00', 'instrumentType': 'OPTSTK', 'instrument': 'Stock Options', 'contract': 'MARUTI 25-Jan-2023', 'expiryDate': '25-Jan-2023', 'optionType': 'Call', 'strikePrice': 8500, 'lastPrice': 143, 'change': 13.55, 'pChange': 10.47, 'volume': 1870200, 'totalTurnover': 306581886, 'value': 306581886, 'premiumTurnOver': 16203281886, 'underlyingValue': 8419, 'openInterest': 2798, 'noOfTrades': 18702, 'meta': {'symbol': 'MARUTI', 'companyName': 'Maruti Suzuki India Limited', 'industry': 'AUTOMOBILES - 4 WHEELERS', 'activeSeries': ['EQ'], 'debtSeries': [], 'tempSuspendedSeries': ['IL'], 'isFNOSec': True, 'isCASec': False, 'isSLBSec': True, 'isDebtSec': False, 'isSuspended': False, 'isETFSec': False, 'isDelisted': False, 'isin': 'INE585B01010'}}
{'underlying': 'RELIANCE', 'identifier': 'OPTSTKRELIANCE25-01-2023CE2600.00', 'instrumentType': 'OPTSTK', 'instrument': 'Stock Options', 'contract': 'RELIANCE 25-Jan-2023', 'expiryDate': '25-Jan-2023', 'optionType': 'Call', 'strikePrice': 2600, 'lastPrice': 25.95, 'change': -14.3, 'pChange': -35.53, 'volume': 4438500, 'totalTurnover': 130269975, 'value': 130269975, 'premiumTurnOver': 11670369975, 'underlyingValue': 2516.65, 'openInterest': 15109, 'noOfTrades': 17754, 'meta': {'symbol': 'RELIANCE', 'companyName': 'Reliance Industries Limited', 'industry': 'REFINERIES', 'activeSeries': ['EQ'], 'debtSeries': [], 'tempSuspendedSeries': [], 'isFNOSec': True, 'isCASec': False, 'isSLBSec': True, 'isDebtSec': False, 'isSuspended': False, 'isETFSec': False, 'isDelisted': False, 'isin': 'INE002A01018'}}

You can use pd.DataFrame.from_records to construct your dataframe:您可以使用pd.DataFrame.from_records来构建您的 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")

Another option is to use standard csv module:另一种选择是使用标准csv模块:

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 :写入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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM