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

时间:2015-01-22 01:45:41

标签: python csv merge

有人可以告诉我如何将两个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)

这不起作用:(

提前致谢

2 个答案:

答案 0 :(得分:0)

假设他们拥有相同的密钥,只需多次调用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)

答案 1 :(得分:0)

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)