简体   繁体   English

Python 字典到 .csv 中的特定格式

[英]Python Dictionary to a specific format in .csv

I have a dictionary in python in this way我以这种方式在python中有一本字典

 my_dict = {'1':['a','b','c'], '2':['d','e','f']}

and i want to write a csv file in which it is displayed as it follows我想写一个 csv 文件,它显示如下

1, a b c
2, d e f

because it is parsed by another application in this specific format.因为它是由另一个应用程序以这种特定格式解析的。

Is there any way to it?有什么办法吗?

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

This is a way to do it:这是一种方法:

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])

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

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