![](/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.