简体   繁体   中英

Writing out a csv file from list of dictionary in python

I'm pretty new to Python and I'm struggling to save a list of dictionary in a csv file.

I want to write out my list in a csv file ,using pipe character as the delimiter

My list is :

[{'COAST': {'Max_Load': 18779, 'Month': 8, 'Day': 13, 'Hour': 17, 'Year': 2013}}, 
 {'EAST': {'Max_Load': 2380, 'Month': 8, 'Day': 5, 'Hour': 17, 'Year': 2013}}, 
 {'FAR_WEST': {'Max_Load': 2281, 'Month': 6, 'Day': 26, 'Hour': 17, 'Year': 2013}}, 
 {'NORTH': {'Max_Load': 1544, 'Month': 8, 'Day': 7, 'Hour': 17, 'Year': 2013}}, 
 {'NORTH_C': {'Max_Load': 24415, 'Month': 8, 'Day': 7, 'Hour': 18, 'Year': 2013}}, 
 {'SOUTHERN': {'Max_Load': 5494.157645, 'Month': 8, 'Day': 8, 'Hour': 16, 'Year': 2013}}, 
 {'SOUTH_C': {'Max_Load': 11433, 'Month': 8, 'Day': 8, 'Hour': 18, 'Year': 2013}}, 
 {'WEST': {'Max_Load': 1862, 'Month': 8, 'Day': 7, 'Hour': 17, 'Year': 2013}}, 
 {'ERCOT': {'Max_Load': 67595, 'Month': 8, 'Day': 7, 'Hour': 17, 'Year': 2013}}]

and my final csv should look like this:

Station|Year|Month|Day|Hour|Max Load

COAST|2013|01|01|10|12345

EAST|2013|01|01|10|12345

FAR_WEST|2013|01|01|10|12345

NORTH|2013|01|01|10|12345 NORTH_C|2013|01|01|10|12345

SOUTHERN|2013|01|01|10|12345

SOUTH_C|2013|01|01|10|12345

WEST|2013|01|01|10|12345

I am trying to write a function save_file to save list in a csv file like above but I get stuck at how to get keys of dictionary to and write them in both row ('COAST') and column ('Year', 'Month', 'Date', 'Hour', 'Max Load').

def save_file(data, filename):
for i in range(len(data)):
    for k,v in data[i].items():
        print k
        for k1,v1 in v.items():
            print k1,v1


with open(filename,'wb') as f:
    fieldnames = ["Station","Year", "Month", "Date", "Hour", "Max Load"]
    wr = csv.writer(f, delimiter="|", fieldnames = fieldnames)
    wr.writeheader()

ANY help would be much appreciated.

You can use csv.DictWriter for writing a dictionary in a csv file :

list_of_dict=[{'COAST': {'Max_Load': 18779, 'Month': 8, 'Day': 13, 'Hour': 17, 'Year': 2013}}, 
 {'EAST': {'Max_Load': 2380, 'Month': 8, 'Day': 5, 'Hour': 17, 'Year': 2013}}, 
 {'FAR_WEST': {'Max_Load': 2281, 'Month': 6, 'Day': 26, 'Hour': 17, 'Year': 2013}}, 
 {'NORTH': {'Max_Load': 1544, 'Month': 8, 'Day': 7, 'Hour': 17, 'Year': 2013}}, 
 {'NORTH_C': {'Max_Load': 24415, 'Month': 8, 'Day': 7, 'Hour': 18, 'Year': 2013}}, 
 {'SOUTHERN': {'Max_Load': 5494.157645, 'Month': 8, 'Day': 8, 'Hour': 16, 'Year': 2013}}, 
 {'SOUTH_C': {'Max_Load': 11433, 'Month': 8, 'Day': 8, 'Hour': 18, 'Year': 2013}}, 
 {'WEST': {'Max_Load': 1862, 'Month': 8, 'Day': 7, 'Hour': 17, 'Year': 2013}}, 
 {'ERCOT': {'Max_Load': 67595, 'Month': 8, 'Day': 7, 'Hour': 17, 'Year': 2013}}]

import csv

with open('names.csv', 'w') as csvfile:
    fieldnames = ('Station','Year', 'Month', 'Day', 'Hour', 'Max_Load')
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter='|')
    writer.writeheader()
    for d in list_of_dict:
          k,v=d.items()[0]
          v['Station']=k
          writer.writerow(v)
Here you go:

lst=...

subkeys=["Year","Month","Day","Hour","Max_Load"]
with open("test.csv", "w") as f:
    f.write("Station|Year|Month|Day|Hour|Max Load\n\n")
    for elem in lst:
        for key in elem.keys():
            f.write(key)
            f.write("|")
            for k, subkey in enumerate(subkeys):
                f.write(str(elem[key][subkey]))
                if k < len(subkeys)-1: f.write("|")
            f.write("\n\n")

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