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

时间:2020-09-04 22:28:01

标签: python csv dictionary

我有字典:

{
    "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列中分别为开,高,低)?

3 个答案:

答案 0 :(得分:1)

在将数据写入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) 

答案 1 :(得分:1)

您可以使用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

答案 2 :(得分:0)

这可能会帮助您

# 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])

谢谢