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

Yng*_*gve 4 python csv excel dictionary

我有一个字典列表,我希望能够在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])
Run Code Online (Sandbox Code Playgroud)

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

key  value
key  value
Run Code Online (Sandbox Code Playgroud)

我想要的是这个:

key   key   key

value value value
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何做到这一点,所以帮助将不胜感激.此外,我希望列名称是字典键,而不是默认的'A,B,C'等.抱歉,如果这是愚蠢的.

谢谢

Ale*_*mer 6

csv模块有一个DictWriter类,在另一个SO答案中很好地涵盖了它.关键点在于,在实例化DictWriter时需要知道所有列标题.您可以从list_of_dicts构造字段名称列表,如果是,则代码变为

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()
Run Code Online (Sandbox Code Playgroud)

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

您也可以for通过单次调用替换循环writer.writerows(list_of_dicts)并使用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)
Run Code Online (Sandbox Code Playgroud)