Python:将嵌套字典写入CSV [英] Python: Writing Nested Dictionary to CSV

查看:665
本文介绍了Python:将嵌套字典写入CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将嵌套字典写入.csv文件.这是一个简单的示例:

I'm trying to write a nested dictionary to a .csv file. Here is is a simple example:

import csv
import itertools

fields = [ 'org', '2015', '2014', '2013' ]
dw     = { 'orgname1': { '2015' : 2, '2014' : 1, '2013' : 1 },
           'orgname2': { '2015' : 1, '2014' : 2, '2013' : 3 },
           'orgname3': { '2015' : 1, '2014' : 3, '2013' : 1 }
        }

with open("test_output.csv", "wb") as f:
    w = csv.writer( f )
    years = dw.values()[0].keys()
    for key in dw.keys():
        w.writerow([key, [dw[key][year] for year in years]])

这使我得到一个包含两列的表:第一列包含orgname;第二列包含orgname.第二个包含[2,1,1](或子词典中的相应值).我想要一个包含四列的表:一列用于orgname,三列用于相应的列表元素.

This gets me a table with two columns: the first contains orgname; the second contains [2, 1, 1] (or the corresponding values from the sub-dictionary). I'd like a table with four columns: one for orgname and then three for the corresponding list elements.

推荐答案

更改:

w.writerow([key, [dw[key][year] for year in years]])

收件人:

w.writerow([key] + [dw[key][year] for year in years])

否则,您尝试将[orgname1, [2, 1, 1]]之类的内容写到csv中,而您的意思是[orgname1, 2, 1, 1].

Otherwise, you try to write something like [orgname1, [2, 1, 1]] to the csv, while you mean [orgname1, 2, 1, 1].

如Padraic所述,您可能希望将years = dw.values()[0].keys()更改为years = sorted(dw.values()[0].keys())years = fields[1:]以避免随机行为.

As Padraic mentioned, you may want to change years = dw.values()[0].keys() to years = sorted(dw.values()[0].keys()) or years = fields[1:] to avoid random behaviour.

这篇关于Python:将嵌套字典写入CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆