如何将两个 python 词典写入单个 csv?

How to write two python dictionaries to a single csv?

谁能告诉我如何将两个 dict 写入一个 csv? 我试过一个字典:

import csv

my_dict = {"test": 1, "testing": 2}

with open('mycsvfile.csv', 'wb') as f:  # Just use 'w' mode in 3.x
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()
    w.writerow(my_dict)

但是当我尝试使用两个 dict:

import csv

my_dict1 = {"test": 1, "testing": 2}
my_dict2 = {"test": 3, "testing": 4}

my_dict =my_dict1,my_dict2
with open('mycsvfile.csv', 'wb') as f:  # Just use 'w' mode in 3.x
    w = csv.DictWriter(f, my_dict1.keys())
    w.writeheader()
    w.writerow(my_dict)

那行不通:(

提前致谢

只需调用 writerow 多次,假设它们具有相同的密钥。

import csv

my_dict1 = {"test": 1, "testing": 2}
my_dict2 = {"test": 3, "testing": 4}

with open('mycsvfile.csv', 'wb') as f:  # Just use 'w' mode in 3.x
    w = csv.DictWriter(f, my_dict1.keys())
    w.writeheader()
    w.writerow(my_dict1)
    w.writerow(my_dict2)

csv.DictWriter对象有一个writerows方法可以满足您的需求:

import csv

my_dict1 = {"test": 1, "testing": 2}
my_dict2 = {"test": 3, "testing": 4}

my_dicts = my_dict1,my_dict2

with open('mycsvfile.csv', 'wb') as f:  # Just use 'w' mode in 3.x
    w = csv.DictWriter(f, my_dict1.keys())
    w.writeheader()
    w.writerows(my_dicts)