我正在使用以下函数在python中将given_dict写入csv并在下面收到以下错误。知道我做错了什么吗?
def write_dict_as_csv(given_dict):
... with open('dict.csv', 'wb') as csv_file:
... writer = csv.writer(csv_file)
... writer.writerow(given_dict.keys())
... writer.writerows(zip(*given_dict.values()))
错误:
>>> write_dict_as_csv(python_csv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in print_dict_as_csv
TypeError: an integer is required
使用测试用例的其他信息:
import csv
#this is a test case which is used to test the functions
def test_normalization_function():
x1 = {'k1': 'a1', 'k2': 'b1'}
x2 = {'k2': 'b2', 'k3': 'c2'}
x3 = {'k1': 'a3'}
x = [x1,x2,x3]
y = normalization(x)
# print('')
for k in y:
print('key: {} : {}'.format(k, y[k]))
with open('mycsvfile.csv', 'wb') as f: # Just use 'w' mode in 3.x
w = csv.DictWriter(f, y.keys())
w.writeheader()
w.writerow(y)
def normalization(list_of_dict):
super_dict = {}
column_counter = 0
for i_dict in list_of_dict:
for k, v in i_dict.iteritems():
if k not in super_dict:
super_dict[k] = []
for i in range(column_counter):
super_dict[k].append('NONE')
super_dict[k].append(v)
column_counter += 1
for k in super_dict:
if k not in i_dict:
super_dict[k].append('NONE')
return super_dict
运行test_normalization_function()时代码的输出:
>>> test_normalization_function()
key: k3 : ['NONE', 'c2', 'NONE']
key: k2 : ['b1', 'b2', 'NONE']
key: k1 : ['a1', 'NONE', 'a3']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in test_normalization_function
TypeError: an integer is required
它显示字典可以打印。但是当我尝试将其保存在csv文件中时,它会出错。