Writing the data directly
import csv
DICT = {a:a*a for a in [1,2,3,4,5]}
n = [2, 5, 99, 3]
headings = ['dict', 'list']
##Writing to .cvs file
with open("try.csv", 'w') as fp:
a = csv.writer(fp)
a.writerow(headings)
for name in n:
if name in DICT:
a.writerow([name, DICT[name]])
else:
a.writerow([name, "Not Available"])
This will result in try.csv
containing:
dict,list
2,4
5,25
99,Not Available
3,9
Doing the processing first, then writing the processed rows:
You can also do the processing and write everything at once:
import csv
DICT = {a:a*a for a in [1,2,3,4,5,6]}
ns = [2,3,99,5]
headings = ['dict', 'list']
ns_squared = [DICT[name] if name in DICT else "NOT_FOUND" for name in names]
print(ns_squared) #=> [4, 9, 'NOT_FOUND', 25]
rows = zip(ns,ns_squared)
with open("try.csv", 'w') as fp:
a = csv.writer(fp)
a.writerow(headings)
a.writerows(rows)
This will then result in:
dict,list
2,4
3,9
99,NOT_FOUND
5,25
Using zip to turn columns into row
If you have columns as lists, you can turn these into rows by using the zip()
builtin function. For example:
>>> column1 = ["value", 1, 2, 3, 4]
>>> column2 = ["square", 2, 4, 9, 16]
>>> zip(column1,column2)
[('value', 'square'), (1, 2), (2, 4), (3, 9), (4, 16)]