writerows
需要iterables的列表。嘗試使用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: ,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中,則顯示「不可用」字樣。
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)
Paul謝謝。 n實際上是一個列表。這很重要嗎? – gJg
然後只需寫'a.writerow(n)'。這會給你頭部列表,就像我例子中的名字一樣。假設你將得到DICT的值,那麼你可以按照'a.writerow(DICT.get(name,「Not Available」)的名字在n)' – PaulMcG
更多信息:我有一個DICT = {1:a, 2:b,3:c,4:d}和一個列表= [1,2,5,6]我rund for循環檢查列表中的項目是否在DICT鍵如果是的話我希望它返回列表項和DICT密鑰。在csv的兩個colums中。希望它更清晰。謝謝 – gJg