【问题标题】:How to convert a Dictionary to CSV file?如何将字典转换为 CSV 文件?
【发布时间】:2020-12-24 04:03:50
【问题描述】:

我有一本字典:

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

【问题讨论】:

标签: python csv dictionary


【解决方案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) 

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      这可能对你有帮助

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

      谢谢

      【讨论】:

      • 这不适用于嵌套字典。
      猜你喜欢
      • 1970-01-01
      • 2018-08-13
      • 2021-12-22
      • 2017-03-27
      • 2023-02-24
      • 2016-01-28
      • 2021-12-18
      • 2011-03-06
      • 2021-12-22
      相关资源
      最近更新 更多