Hard code the header with the order you want.
keys = ['Date', 'RSD', 'GBP']
with open(file, 'wt') as output_file:
dict_writer = csv.DictWriter(output_file, keys, lineterminator = '\n')
dict_writer.writeheader()
dict_writer.writerows(hist)
Use an OrderedDict if you want order and reverse:
from collections
import OrderedDict
for x in dates:
l = OrderedDict()
for y in currs:
try:
m = exrates.get_exrates(x)[y]
except KeyError:
m = '-'
l[y] = m
l['Date'] = x
hist.append(l)
To get the reverse order use reversed:
keys = list(reversed(list(hist[0].keys()))) print(keys)
If you just want to have the last key atthe front:
k = list(hist[0].keys()) keys = keys[-1] + key[: -1] print(keys)
If you are going to supply the headers and don't want ordered dicts after just write as you go, presuming curr is a list you can use curr as the header adding Date:
import csv
with open(file, 'wt') as output_file:
wr = csv.writer(output_file)
wr.writerow(["Date"] + currs)
for x in dates:
row = [x] + [exrates.get_exrates(x).get(y, "-") for y in currs]
wr.writerow(row)
(If you're not averse to using pandas
) You could do this by simply re-ordering the columns, look at the last step:
In[1]: import pandas as pd
In[2]: x = [{
'RSD': '-',
'GBP': '0.500409',
'Date': '2008-04-05'
},
...: {
'RSD': '-',
'GBP': '0.500409',
'Date': '2008-04-06'
},
...: {
'RSD': '-',
'GBP': '0.50331',
'Date': '2008-04-07'
},
...: {
'RSD': '-',
'GBP': '0.507939',
'Date': '2008-04-08'
},
]
In[3]: pd.DataFrame(x)
Out[3]:
Date GBP RSD
0 2008 - 04 - 05 0.500409 -
1 2008 - 04 - 06 0.500409 -
2 2008 - 04 - 07 0.50331 -
3 2008 - 04 - 08 0.507939 -
In[4]: y = pd.DataFrame(x)
In[5]: y = y[['RSD', 'GBP', 'Date']]
In[6]: y
Out[6]:
RSD GBP Date
0 - 0.500409 2008 - 04 - 05
1 - 0.500409 2008 - 04 - 06
2 - 0.50331 2008 - 04 - 07
3 - 0.507939 2008 - 04 - 08
Last Updated : 01 Jul, 2020
import csv
field_names = ['No', 'Company', 'Car Model']
with open('Names.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames = field_names)
writer.writeheader()
writer.writerows(cars)
Syntax:
DictWriter((filename), fieldnames = [list of field names])
The final step is to read budget2.csv into a spreadsheet. The result is displayed in Figure 6 (in LibreOffice one must specify in the Open dialog that the spreadsheet data are separated by commas, i.e., that the file is in CSV format). , You may wonder why we used the csv module to read and write CSV files when such files have comma separated values, which we can extract by splitting lines with respect to the comma (this technique is used in the section Example: Reading and plotting data recorded at specific dates to read a CSV file): , Our final task is to write the modified table list back to a CSV file so that the data can be loaded in a spreadsheet program. The write task is done by the code segment , The row variable is a list of column values that are read from the file by the csv module. The three lines computing table can be condensed to one using a list comprehension:
, "year 1", "year 2", "year 3"
"person 1", 651000, 651000, 651000
"person 2", 1100500, 950100, 340000 "person 3", 740000, 780000, 800000
infile = open('budget.csv', 'r') # CSV file import csv table = [] for row in csv.reader(infile): table.append(row) infile.close()
table = [row for row in csv.reader(infile) ]
import pprint
pprint.pprint(table)
[
['', 'year 1', 'year 2', 'year 3'],
['person 1', '651000', '651000', '651000'],
['person 2', '1100500', '950100', '340000'],
['person 3', '740000', '780000', '800000']
]
for r in range(1, len(table)):
for c in range(1, len(table[0])):
table[r][c] = float(table[r][c])
I am trying to export a list of dictionaries to a .csv file:, 2 days ago Jun 04, 2022 · You can append a dictionary to CSV file using CSV.writer() method and CSV.writerow() method. ... Also You should make sure that the order of columns of the csv file should be same as the order of the keys present in the dictionary. Otherwise, the data appended to the csv file will become inconsistent and will lead to errors. ... , This method is used to write a row of data into the given file. In Python to access a new CSV file and add the dictionary into it. In this example, we use the CSV writer () method. In Python, the CSVwriter () method helps the user to convert the user data into a string. ,My list of dictionaries (hist) is:
keys = hist[0].keys() with open(file, 'wt') as output_file: dict_writer = csv.DictWriter(output_file, keys, lineterminator = '\n') dict_writer.writeheader() dict_writer.writerows(hist)
from collections
import OrderedDict
for x in dates: l = OrderedDict() for y in currs: try: m = exrates.get_exrates(x)[y] except KeyError: m = '-'
l[y] = m l['Date'] = x hist.append(l)
csv.DictWriter(f, fieldnames, restval = '', extrasaction = 'raise', dialect = 'excel', * args, ** kwds)
csv.DictWriter(f, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)
import csv columns = ['Name', 'Mark', 'Subject'] Student_dict = [{
'Name': 'Jack',
'Mark': 100,
'Subject': 'Math'
}, {
'Name': 'Rack',
'Mark': 100,
'Subject': 'Math'
}, {
'Name': 'Max',
'Mark': 100,
'Subject': 'Music'
}, {
'Name': 'David',
'Mark': 100,
'Subject': 'Math'
}, {
'Name': 'Tawn',
'Mark': 100,
'Subject': 'Physic'
}, ]
try: with open("students.csv", 'w', newline = '') as csvfile: writer = csv.DictWriter(csvfile, fieldnames = columns) writer.writeheader() for key in Student_dict: writer.writerow(key) except IOError: print("I/O error")
import csv columns = ['Name','Mark','Subject'] Student_dict = [
{'Name': 'Jack','Mark': 100, 'Subject': 'Math'}, { 'Name': 'Rack', 'Mark': 100,'Subject': 'Math'}, { 'Name': 'Max', 'Mark': 100,'Subject': 'Music'}, { 'Name': 'David', 'Mark':100,'Subject': 'Math'}, { 'Name': 'Tawn', 'Mark': 100,'Subject': 'Physic'}, ] try:
with open("students.csv", 'w',newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=columns)
writer.writeheader()
for key in Student_dict: writer.writerow(key) except IOError:
print("I/O error")
import csv Student_dict = [{
'Name': 'Jack',
'Mark': 100,
'Subject': 'Math'
}, {
'Name': 'Rack',
'Mark': 100,
'Subject': 'Math'
}, {
'Name': 'Max',
'Mark': 100,
'Subject': 'Music'
}, {
'Name': 'David',
'Mark': 100,
'Subject': 'Math'
}, {
'Name': 'Tawn',
'Mark': 100,
'Subject': 'Physic'
}, ] keys = Student_dict[0].keys() with open("students.csv", "w") as file: csvwriter = csv.DictWriter(file, keys) csvwriter.writeheader() csvwriter.writerows(Student_dict)
Name Mark Subject Jack 100 Math Rack 100 Math Max 100 Music David 100 Math Tawn 100 Physic
import csv columns = ['Name', 'Mark', 'Subject', 'Age'] Student_dict = [{ 'Name': 'Jack', 'Mark': 100, 'Subject': 'Math' }, { 'Name': 'Rack', 'Mark': 100, 'Subject': 'Math' }, { 'Name': 'Max', 'Mark': 100, 'Subject': 'Music' }, { 'Name': 'David', 'Mark': 100, 'Subject': 'Math' }, { 'Name': 'Tawn', 'Mark': 100, 'Subject': 'Physic' }, ] with open("student.csv", "w") as File: csvwriter = csv.DictWriter(File, fieldnames = columns, restval = "NA") csvwriter.writeheader() # write header csvwriter.writerows(Student_dict)
import csv columns = ['Name','Mark','Subject','Age'] Student_dict = [
{'Name': 'Jack','Mark': 100, 'Subject': 'Math'}, { 'Name': 'Rack', 'Mark': 100,'Subject': 'Math'}, { 'Name': 'Max', 'Mark': 100,'Subject': 'Music'}, { 'Name': 'David', 'Mark':100,'Subject': 'Math'}, { 'Name': 'Tawn', 'Mark': 100,'Subject': 'Physic'}, ] with open("student.csv", "w") as File: csvwriter = csv.DictWriter(File, fieldnames=columns, restval="NA") csvwriter.writeheader() # write header csvwriter.writerows(Student_dict)
Name Mark Subject Age Jack 100 Math NA Rack 100 Math NA Max 100 Music NA David 100 Math NA Tawn 100 Physic NA