Python: 将字典以 table-like 格式转储到 csv 文件的列中

Python: dumping dictionaries to columns of a csv file in a table-like format

我有 d1, d2, ..., dn 个相同 len 的词典,需要将它们转储到新 csv 文件的列中。

我希望文件具有 headers 并且看起来很像这样:

        |STAGE 1      | |STAGE 2               | |TOTAL                |
SIM     d1  d2  d3  d4  d5  d6  d7  d8  d9  d10  d11  d12  d13  d14  d15    
event 1
event 2
event 3
event 4
event n

每个 d 列都应该有相应 dictionary 的值在下面对齐,tab 应该可以很好地分隔每一列。

我知道我可以像这样创建一个 csv 文件:

import csv

my_d = {"STAGE 1": 1, "STAGE 2": 2, "TOTAL": 3}

with open('mycsvfile.csv', 'wb') as csvfile:  
    w = csv.DictWriter(csvfile, my_d.keys())
    w.writeheader()
    w.writerow(my_d)

但我似乎找不到出路,而且我也没有弄清楚如何让 headers 像 d1 一样显示为 sub-headers。在 Python 中如何做到这一点?

如果您转置列表,您将能够写入类似于您的示例的 csv

h1 = ['a','b','c','d','e']
d1 = [1, 2, 3, 4, 5]
d2 = [1, 2, 3, 4, 5]
d3 = [1, 2, 3, 4, 5]

transpose =  [h1, d1, d2, d3]

print(transpose)
print(list(map(list, zip(*transpose)))) 

输出:

>>> 
[['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
[['a', 1, 1, 1], ['b', 2, 2, 2], ['c', 3, 3, 3], ['d', 4, 4, 4], ['e', 5, 5, 5]]
>>> 

假设您使用 Python 3,如果您使用 python 2 print(map(list, zip(*l))) 而不是