[英]Writing a python Dictionary to a CSV file with keys as column headers
[英]Python dictionary keys to csv file with column match
我正在嘗試通過將鍵匹配到csv標頭中的列來將多個字典(鍵和值)推入csv文件。 例:
import csv
d1 = {'a':1, 'b':2, 'c': 3}
d2 = {'d':4, 'e':5, 'f': 6}
with open('my_data.csv','wb') as f:
w = csv.writer(f)
w.writerow(['a', 'b', 'c', 'd', 'e', 'f'])
#iterate through all keys in d1,d2,dn
#if key matches column:
#write value of key to the bottom of column
#else:
#error key not found in header
mydata.csv中的預期結果
a,b,c,d,e,f
1,2,3,4,5,6
答案是..不僅將列名傳遞給writerow()..將它們放在變量columns
,然后使用它來控制值的寫出順序。 Python字典沒有順序。您必須使用一些代碼才能將值排序為所需的順序。
代碼的最后一行將這些值寫到CSV中,使用了一個名為List Comprehension的python功能。 這是保存3-4行代碼的快捷方式。 查一下,它們非常方便。
import csv
d1 = {'a':1, 'b':2, 'c': 3}
d2 = {'d':4, 'e':5, 'f': 6}
columns = ['a', 'b', 'c', 'd', 'e', 'f']
# combine d1 and d2 into data.. there are other ways but this is easy to understand
data = dict(d1)
data.update(d2)
with open('my_data.csv','wb') as f:
w = csv.writer(f)
w.writerow(columns)
# make a list of values in the order of columns and write them
w.writerow([data.get(col, None) for col in columns])
如果沒有列表理解,這會是什么樣子:
row = []
for col in columns:
row.append(data.get(col, None))
w.writerow(row)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.