简体   繁体   English

Python:如何将元组值字典写入 csv 文件?

[英]Python: How to write a dictionary of tuple values to a csv file?

How do I print the following dictionary into a csv file?如何将以下字典打印到 csv 文件中?

maxDict = {'test1': ('alpha', 2), 'test2': ('gamma', 2)} 

So, that the output CSV looks as follows:因此,输出 CSV 如下所示:

test1, alpha, 2
test2, gamma, 2
import csv
with open("data.csv", "wb") as f:
    csv.writer(f).writerows((k,) + v for k, v in maxDict.iteritems())
maxDict = {'test1': ('alpha', 2), 'test2': ('gamma', 2)}
csvData = []
for col1, (col2, col3) in maxDict.iteritems():
  csvData.append("%s, %s, %s" % (col1, col2, col3))
f = open('test.csv', 'w')
f.write("\n".join(csvData))
f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM