2017-08-01 75 views
0

尝试使用字典填充CSV文件。Dictionary to CSV

这里是我想要的代码:

import csv 

my_dict = {'App 1': 'App id1', 'App 2': 'App id2', 'App 3': 'App id3'} 
with open('test.csv', 'w') as f: 
    fieldnames = ['Application Name', 'Application ID'] 
    writer = csv.DictWriter(f, fieldnames=fieldnames) 
    writer.writeheader() 
    writer.writerows(my_dict) 

有了这个代码,它只是创造与头一个CSV文件。

我在寻找一个类似的输出:

enter image description here

+2

不错的尝试!保持!有没有需要回答的问题? –

+0

[我如何将Python字典写入csv文件?](https://stackoverflow.com/questions/10373247/how-do-i-write-a-python-dictionary-to-a-csv -file) –

+0

谢谢Alan。 @Moses的回答给了我很多帮助。 – Raj

回答

3

您需要将数据重新格式化为类型的字典列表,例如从旧字典键和值放置作为值对字段名中新类型的字典:

my_dict = {'App 1': 'App id1', 'App 2': 'App id2', 'App 3': 'App id3'} 
with open('test.csv', 'w') as f: 
    fieldnames = ['Application Name', 'Application ID'] 
    writer = csv.DictWriter(f, fieldnames=fieldnames) 
    writer.writeheader() 
    data = [dict(zip(fieldnames, [k, v])) for k, v in my_dict.items()] 
    writer.writerows(data) 
+0

谢谢!这几乎解决了我的问题。但是,我在csv文件中的字典中的每个项目之后都会出现空行。有没有解决方法? – Raj

+1

@Raj很常见的问题,请看:https://stackoverflow.com/questions/3348460/csv-file-written-with-python-has-blank-lines-between-each-row –

+0

非常感谢@Moses – Raj

0

你也可以做到这一点没有代码的进口和更少的行:

my_dict = {'App 1': 'App id1', 'App 2': 'App id2', 'App 3': 'App id3'} 
with open('test.csv', 'w') as f: 
    f.write('Application Name, Application ID\n') 
    for key in my_dict.keys(): 
     f.write("%s,%s\n"%(key,my_dict[key]))