简体   繁体   中英

How to convert a Dictionary to CSV file?

I have a 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",
        ...

How would I write this to a csv file (with dates in column A, open, high, low in columns b,c,d, respectively)?

You've got to work a little on the data before writing it to CSV. You may want to create of list of dictionaries that represent your CSV rows before writing the 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) 

You could do it fairly succinctly by using a 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))

Resulting CSV file's contents:

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

This Might help you

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

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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