![](/img/trans.png)
[英]How to create a dictionary with one key and multiple values from a CSV file?
[英]how to write a dictionary with one key multiple values to a csv file
我有以下形式的字典
>>> {'1' : [V3210 , 234567 ,1235675 , 23], '2' : [v3214 , 5678 ,65879 ,89} , ...}
如何將此字典寫入csv文件?
謝謝
使用內置的csv模塊。 假設您要使用key,value1,value2,...
格式。
import csv
with open('filename', 'w') as f:
c = csv.writer(f)
for key, value in d.items():
c.writerow([key] + value)
假設數字鍵是行號,請嘗試如下操作:
theDict = {'1' : [V3210 , 234567 ,1235675 , 23], '2' : [v3214 , 5678 ,65879 ,89] }
largestkey=max(map(int,theDict.keys()))
with file("out.csv") as f:
for linenum in range(largestkey+1):
f.write(",".join(theDict[str(linenum)])
f.write("\n")
您需要查看Python的字符串API,列表處理和文件處理,以更加熟悉Python。
使用Python的csv
模塊將使此操作變得非常簡單:
import csv
d = {'1' : ['V3210', 234567, 1235675, 23], '2' : ['v3214', 5678, 65879 ,89], }
with open('output.csv', 'wb') as csvfile:
csv.writer(csvfile).writerows([row[0]] + row[1] for row in d.iteritems())
請注意,Python 3中沒有使用iteritems()
字典方法,因此您需要使用d.items()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.