如何在python中联合适用于csv.DictWriter()的OrderedDicts的dict?

时间:2017-11-23 11:32:54

标签: python csv ordereddictionary

如何确保字典中的所有OrderedDicts都拥有完整的所有密钥集,以便可以从中生成CSV?

所以从这里开始:

    unaggregated = {
        1: OrderedDict([
            ('column_a', 'foo'),
            ('column_b', 'bar'),
        ]),
        2: OrderedDict([
            ('column_a', 'baz'),
        ]),
    }

到此:

    aggregated = {
        1: OrderedDict([
            ('column_a', 'foo'),
            ('column_b', 'bar'),
        ]),
        2: OrderedDict([
            ('column_a', 'baz'),
            ('column_b', None),
        ]),
    }

我是这样生成我的CSV,也许是因为复杂的数据结构。

    fieldnames = next(iter(aggregated.values())).keys()
    writer = csv.DictWriter(output_file, fieldnames)
    writer.writeheader()
    for id in aggregated:
        writer.writerow(aggregated[id])

谢谢!

0 个答案:

没有答案