繁体   English   中英

如何将字典转换为 CSV 文件?

[英]How to convert a Dictionary to CSV file?

我有一本字典:

{
    "2020-09-03": {
        "1. open": "128.1900",
        "2. high": "129.9500",
        "3. low": "123.6500",
        "4. close": "124.4500",
        "5. volume": "5716750"
    },
    "2020-09-02": {
        "1. open": "123.7200",
        "2. high": "123.567",
        ...

我将如何将其写入 csv 文件(A 列中的日期,b、c、d 列中分别为打开、高、低)?

在将数据写入 CSV 之前,您必须对数据进行一些处理。 在编写 CSV 之前,您可能希望创建代表 CSV 行的字典列表:

import csv
x = {'2020-09-03': {'1. open': '128.1900', '2. high': '129.9500', '3. low': '123.6500', '4. close': '124.4500', '5. volume': '5716750'},
  '2020-09-02': {'1. open': '123.7200', '2. high': '129.9500', '3. low': '19.9500'}}
data = [] #list of data to be written
for k,v in x.items(): #iterate through rows of dictionary x
    f = {} #dictionary to which all data gather for each iteration is held
    f['date'] = k #get date
    f['open'] = v['1. open'] #get open
    f['high'] = v['2. high'] #get high
    f['low'] = v['3. low'] #get low
    data.append(f) # append dictionary f to data list
   
header = ['date', 'open', 'high', 'low'] #set CSV column headers

# open the csv file in write mode 
file = open('arngcsv.csv', 'w', newline ='') 
with file: 
    # identifying header   
    writer = csv.DictWriter(file, fieldnames = header) 
    # write data row-wise into the csv file 
    writer.writeheader()
    for row in data:
        writer.writerow(row) 

您可以使用csv.DictWriter相当简洁地完成此操作。

import csv

my_dict = {
              "2020-09-03": {
                  "1. open": "128.1900",
                  "2. high": "129.9500",
                  "3. low": "123.6500",
                  "4. close": "124.4500",
                  "5. volume": "5716750"
              },
              "2020-09-02": {
                  "1. open": "123.7200",
                  "2. high": "123.567",
                  "3. low": "123.6500",
                  "4. close": "128.3450",
                  "5. volume": "6745450"
              },
          }

filename = 'converted_dict.csv'
fieldkeys = ['1. open', '2. high', '3. low']
fieldnames = [fieldkey.split()[1] for fieldkey in fieldkeys]
fieldmap = dict(zip(fieldnames, fieldkeys))

with open(filename, 'w', newline='') as file:
    writer = csv.DictWriter(file, ['date'] + fieldnames)
    writer.writeheader()  # If desired.

    for date, values in my_dict.items():
        row = {fieldname: values[fieldmap[fieldname]] for fieldname in fieldnames}
        writer.writerow(dict(date=date, **row))

生成的 CSV 文件的内容:

date,open,high,low
2020-09-03,128.1900,129.9500,123.6500
2020-09-02,123.7200,123.567,123.6500

这可能会帮助你

# For python 2, skip the "newline" argument: open('dict.csv','w")
import csv
with open('dict.csv', 'w') as csv_file:  
    writer = csv.writer(csv_file)
    for key, value in mydict.items():
       writer.writerow([key, value])

谢谢

暂无
暂无

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

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