Python 将字典列表写入csv,其中字典值为列表
这是我到目前为止的代码Python 将字典列表写入csv,其中字典值为列表,python,csv,Python,Csv,这是我到目前为止的代码 list_of_dict = [{'A': [1, 2, 3, 4, 5], 'B': [10, 11]}] with open('result.csv','wb') as out: f1 = csv.DictWriter(out,list_of_dict[0].keys()) f1.writeheader() f1.writerows(list_of_dict) 我得到的输出是 A B [1,2,3,4,5]
list_of_dict = [{'A': [1, 2, 3, 4, 5], 'B': [10, 11]}]
with open('result.csv','wb') as out:
f1 = csv.DictWriter(out,list_of_dict[0].keys())
f1.writeheader()
f1.writerows(list_of_dict)
我得到的输出是
A B
[1,2,3,4,5] [10,11]
我如何得到输出作为
A B
1 10
2 11
3
4
5
您必须将一个字典转换为一个字典列表,输出中每行一个:
import csv
from itertools import izip_longest
with open('result.csv','wb') as out:
keys = list_of_dict[0].keys()
f1 = csv.DictWriter(out, keys)
f1.writeheader()
f1.writerows(dict(zip(keys, row)) for row in izip_longest(*list_of_dict[0].values()))
请注意,这些键将按字典(任意)顺序列出
上述生成器表达式按所需的行生成字典:
>>> from itertools import izip_longest
>>> list_of_dict = [{'A': [1, 2, 3, 4, 5], 'B': [10, 11]}]
>>> keys = list_of_dict[0].keys()
>>> [dict(zip(keys, row)) for row in izip_longest(*list_of_dict[0].values())]
[{'A': 1, 'B': 10}, {'A': 2, 'B': 11}, {'A': 3, 'B': None}, {'A': 4, 'B': None}, {'A': 5, 'B': None}]