writerows
takes a list of iterables. Try using writerow
. From the looks of things, n
is a dict, so to get a row of headers and a row of values, do:
a.writerow(n.keys())
a.writerow(n.values())
You could write a.writerow(n)
for the first line, but I prefer to show this a little more explicitly.
And a little shortcut to add all the default values:
names = ['list','of','all','expected','keys']
data = {'list':'A', 'of':'zoo', 'keys':'foo'}
default = dict.fromkeys(names,"Not Available")
default.update(data)
data = default
Leaving data with the contents:
{'all': 'Not Available', 'of': 'zoo', 'list': 'A', 'expected': 'Not Available', 'keys': 'foo'}
EDIT:
Given DICT = {1:a, 2:b, 3:c, 4:d} and a list n = [1, 2, 5, 6], just do:
a.writerow(n)
a.writerow(DICT.get(name,"Not Available") for name in n)
will print two rows to your CSV file, one with the key names in n, and one with the values from DICT, or the words "Not Available" if a particular key is not in DICT.
EDIT2:
You are trying too hard - DICT.get will take care of whether an entry exists or not:
with open('test_write.csv', 'w') as fp:
a = csv.writer(fp)
a.writerow(n)
a.writerow(DICT.get(name,"Not Available") for name in n)
Here is the same code, with a little more verbose form:
with open('test_write.csv', 'w') as fp:
a = csv.writer(fp)
# write row of header names
a.writerow(n)
# build up a list of the values in DICT corresponding to the keys in n
values = []
for name in n:
if name in DICT:
values.append(DICT[name])
else:
values.append("Not Available")
# or written as a list comprehension:
# values = [DICT[name] if name in DICT else "Not Available" for name in n]
#
# or just use DICT.get, which does the name checking for us, and chooses the
# default value if the key is not found
# values = [DICT.get(name, "Not Available") for name in n]
# now write them out
a.writerow(values)
# or finally, the list build and writerow call all in one line
# a.writerow(DICT.get(name,"Not Available") for name in n)
EDIT:
# to write out the transpose of the previous lines (that is, instead of
# a line of names and a line of the matching values, a line for each
# name-value pair), use Python's zip builtin:
for nameValueTuple in zip(n,values):
a.writerow(nameValueTuple)