简体   繁体   中英

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,

    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. 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 ". 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). If I can have some solution for enabling the same in CSV, that will be great.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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