如何确保字典中的所有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])
谢谢!