我以这种方式在python中有一本字典
my_dict = {'1':['a','b','c'], '2':['d','e','f']}
我想编写一个csv文件,在其中显示
1, a b c
2, d e f
因为它以其特定格式由另一个应用程序解析。
有什么办法吗?
答案 0 :(得分:0)
my_dict = {'1':['a','b','c'], '2':['d','e','f']}
from operator import itemgetter
import csv
with open('data.csv','w') as f:
a = csv.writer(f, delimiter = ',', lineterminator='\n')
for k,v in sorted(my_dict.items(), key=itemgetter(0)):
a.writerow([k,' ' + ' '.join(v)])
data.csv
1, a b c
2, d e f
答案 1 :(得分:0)
这是一种方法:
my_dict = {'1':['a','b','c'], '2':['d','e','f']}
with open('data.csv', 'w') as f:
f.write('\n'.join([("%s, %s" % (k,' '.join(my_dict[k]))) for k in my_dict])