尝试将字典的内容写入.csv文件。字典值是元组。我希望每一行都包含一个键,然后迭代这些值并将每个值写在同一行的单独字段中:
我写了这个函数(其中v是一个元组):
def csv_writer(dict, filename):
with open(filename, 'w') as f:
w = csv.writer(f)
for k,v in dict.items():
w.writerow([k, v])
v的内容在csv文件中显示为元组,但我希望得到这样的内容:
k1 v1 v2 v3 v4
k2 v1 v5 v6
等
提前感谢任何提示。
答案 0 :(得分:1)
使用*v
,也称为splat
。更多信息在docs中:
https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists
答案 1 :(得分:1)
def csv_writer(dict, filename):
with open(filename, 'w') as f:
outfile = csv.writer(f)
for k,v in dict.items():
outfile.writerow([k] + v)