writerows
获取一个可迭代的列表。尝试使用writerow
. 从外观上看,n
是一个字典,所以要获得一行标题和一行值,请执行以下操作:
a.writerow(n.keys())
a.writerow(n.values())
你可以写a.writerow(n)
第一行,但我更喜欢更明确地展示这一点。
还有一个添加所有默认值的快捷方式:
names = ['list','of','all','expected','keys']
data = {'list':'A', 'of':'zoo', 'keys':'foo'}
default = dict.fromkeys(names,"Not Available")
default.update(data)
data = default
留下数据的内容:
{'all': 'Not Available', 'of': 'zoo', 'list': 'A', 'expected': 'Not Available', 'keys': 'foo'}
编辑:
给定 DICT = {1:a, 2:b, 3:c, 4:d} 和列表 n = [1, 2, 5, 6],只需执行以下操作:
a.writerow(n)
a.writerow(DICT.get(name,"Not Available") for name in n)
将在您的 CSV 文件中打印两行,其中一行包含 n 中的键名,另一行包含 DICT 中的值,或者如果特定键不在 DICT 中,则打印“不可用”字样。
编辑2:
您太努力了 - DICT.get 将处理条目是否存在:
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)
这是相同的代码,但形式更冗长:
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)
编辑:
# 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)