将Python字典写入CSV,其中keys=columns,values=rows

2024-05-20 10:59:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典列表,我希望能够在Excel中打开,格式正确。这就是我目前为止使用csv的情况:

list_of_dicts = [{'hello': 'goodbye'}, {'yes': 'no'}]
out_path= "/docs/outfile.txt"
out_file = open(ipath, 'wb')

writer = csv.writer(ofile, dialect = 'excel')

for items in list_of_dicts:
    for k,v in items.items():
        writer.writerow([k,v])

显然,当我在Excel中打开输出时,它的格式如下:

key  value
key  value

我想要的是:

key   key   key

value value value

我不知道怎么做,所以请帮忙。另外,我希望列名是字典键,而不是默认的“A、B、C”等。如果这是愚蠢的,对不起。

谢谢


Tags: ofcsvkeyin列表for字典value
2条回答

您需要编写两个单独的行,一个带有键,一个带有值,而不是:

writer = csv.writer(ofile, dialect = 'excel')

writer.writerow([k for d in list_of_dicts k in d])
writer.writerow([v for d in list_of_dicts v in d.itervalues()])

这两个列表理解首先从输入列表中的词典中提取所有键,然后提取所有值,并将它们组合成一个列表写入CSV文件。

csv模块为此有一个DictWriter类,这在another SO answer中有很好的介绍。关键点是,在实例化DictWriter时,需要知道所有列标题。如果你的代码变成

list_of_dicts = [{'hello': 'goodbye'}, {'yes': 'no'}]
out_path= "/docs/outfile.txt"
out_file = open(out_path, 'wb')

fieldnames = sorted(list(set(k for d in list_of_dicts for k in d)))
writer = csv.DictWriter(out_file, fieldnames=fieldnames, dialect='excel')

writer.writeheader() # Assumes Python >= 2.7
for row in list_of_dicts:
    writer.writerow(row)
out_file.close()

我构建字段名的方式会扫描整个list_of_dicts,因此随着大小的增加,速度会减慢。相反,您应该直接从数据源构造fieldnames,例如,如果数据源也是csv文件,则可以使用听写器并使用fieldnames = reader.fieldnames

您还可以用对writer.writerows(list_of_dicts)的单个调用替换for循环,并使用with块来处理文件关闭,在这种情况下,您的代码将变成

list_of_dicts = [{'hello': 'goodbye'}, {'yes': 'no'}]
out_path= "/docs/outfile.txt"

fieldnames = sorted(list(set(k for d in list_of_dicts for k in d)))

with open(out_path, 'wb') as out_file:
    writer = csv.DictWriter(out_file, fieldnames=fieldnames, dialect='excel')
    writer.writeheader()
    writer.writerows(list_of_dicts)

相关问题 更多 >