简体   繁体   English

在Python中将嵌套的字典打印为CSV

[英]Printing nested dicts to CSV in Python

I am parsing certain text files and keeping track of a number of programs, software versions, and counts of those versions' occurrences, in the following structure: 我正在解析某些文本文件,并以以下结构跟踪许多程序,软件版本以及这些版本的出现次数:

{Excel: {'1.2.1':2, '2.1.1':55, '3.4.5':12},
 Adobe: {'1.1.1':4, '5.4.4':12, '4'3.3':8}[...]}

etc. 等等

How can I print this neatly to CSV so that the output would look like this: 如何将其整齐地打印到CSV,以便输出看起来像这样:

Program,Version,Count
Excel,1.2.1,2
Excel,2.1.1,55
Excel,3.4.5,12
Adobe,1.1.1,4
Adobe,5.4.4,12
Adobe,4.3.3,8

I have done a lot of searching and haven't been able to find exactly what I need. 我已经做了很多搜索,但仍找不到我真正需要的东西。 Any help is appreciated! 任何帮助表示赞赏!

Edit: 编辑:

Here is what I have tried, which I think comes close, but isn't right based on the output I get: 这是我尝试过的方法,我认为这很接近,但是基于我得到的输出,这是不正确的:

for prod,version in products.iteritems():
    for p in prod:
        for v in version:
            outfile.write('%s,%s,%d\n' % (p,v,version[v]))

where products is the name of the outer dict. 产品是外部字典的名称。

Thanks. 谢谢。

The hacky way: 骇客方式:

def print_csv_data(data):
  with open('my_output', 'w') as f:
     f.write('Program,Version,Count')
     for k, v in data.iteritems():
        for id, count in v.iteritems():
           f.write(k+','+id+','+count)

I'd recommend looking at the CSV module though for better use, as the above approach can easily break your document if your ids or program names contain commas. 我建议您查看CSV模块,以更好地使用它,因为如果您的ID或程序名称包含逗号,上述方法很容易破坏您的文档。

import csv

with open('output.csv', 'w') as csvfile:
    fieldnames = ['Program', 'Version', 'Count']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for k, v in data.iteritems():
        for id, count in v.iteritems():
           f.write({'Program':k, 'Version':id, 'Count':count})

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

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