Writing out a csv file from list of dictionary in python -
i'm pretty new python , i'm struggling save list of dictionary in csv file.
i want write out list in csv file ,using pipe character delimiter
my list :
[{'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 final csv should 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 trying write function save_file save list in csv file above stuck @ how keys of dictionary , write them in both row ('coast') , column ('year', 'month', 'date', 'hour', 'max load').
def save_file(data, filename): in range(len(data)): k,v in data[i].items(): print k k1,v1 in v.items(): print k1,v1 open(filename,'wb') f: fieldnames = ["station","year", "month", "date", "hour", "max load"] wr = csv.writer(f, delimiter="|", fieldnames = fieldnames) wr.writeheader()
any appreciated.
you can use csv.dictwriter
writing dictionary in 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 open('names.csv', 'w') csvfile: fieldnames = ('station','year', 'month', 'day', 'hour', 'max_load') writer = csv.dictwriter(csvfile, fieldnames=fieldnames,delimiter='|') writer.writeheader() d in list_of_dict: k,v=d.items()[0] v['station']=k writer.writerow(v)
Comments
Post a Comment