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 ファイルに 2 つの行を出力します。1 つは n のキー名、もう 1 つは DICT からの値、または特定のキーが DICT にない場合は「利用できません」という単語です。
EDIT2:
あなたは頑張りすぎています - 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)