简体   繁体   English

在python中将列表字典写入CSV文件

[英]Write a dictionary of list to CSV file in python

I have dictionary as follows {a: [1, 2], b: [4, 5, 6]} and I would like to write it to a CSV file as follows,我有如下字典{a: [1, 2], b: [4, 5, 6]}我想将它写入一个 CSV 文件,如下所示,

    Col1 Col2
Row1 a
Row2      1
Row3      2
Row4 b
Row5      4
Row6      5
Row7      6

Any help is appreciated, thanks!任何帮助表示赞赏,谢谢! Though there are multiple similar questions of this type in the forum, I am still looking for an answer because I want to do write this to a csv file.尽管论坛中有多个此类类似问题,但我仍在寻找答案,因为我想将其写入 csv 文件。 To help further I am exactly trying to replicate the solution for the question from this discussion in the past - " Write dictionary values in an excel file ".为了进一步提供帮助,我正试图从过去的讨论中复制问题的解决方案 - “ 在 excel 文件中写入字典值”。 But the problem is it gives solution for writing into an excel file that needs a custom library to be imported (for which I don't have access).但问题是它提供了写入需要导入自定义库(我无权访问)的 excel 文件的解决方案。 If I can have some solution for enabling the same in CSV, that will be great.如果我可以有一些在 CSV 中启用相同的解决方案,那就太好了。

You can try this:你可以试试这个:

import csv
s = {'a': [1, 2], 'b': [4, 5, 6]}
final_data = [['Row{}'.format(i), c] for i, c in enumerate([h for c in [[d] if not isinstance(d, list) else d for g in sorted(s.items(), key=lambda x:x[0]) for d in g] for h in c])]
with open('row_results.csv', 'w') as f:
  write = csv.writer(f)
  write.writerows([["Col{}".format(i+1) for i in range(len(s))]]+final_data)

Output:输出:

Col1,Col2
Row0,a
Row1,1
Row2,2
Row3,b
Row4,4
Row5,5
Row6,6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM