-2

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.

s73
  • 51
  • 8
  • 1
    Take a look at this answer : https://stackoverflow.com/questions/10373247/how-do-i-write-a-python-dictionary-to-a-csv-file – Chuk Ultima Feb 08 '18 at 08:07
  • I want the keys to be written in a separate column as against the rows (which is how it is written in the example which you have given above). Also I need guidance on writing the values of each key into adjacent column. – s73 Feb 08 '18 at 08:16
  • Possible duplicate of [Python Dictionary to CSV](https://stackoverflow.com/questions/8331469/python-dictionary-to-csv) – Dennis Tsoi Feb 08 '18 at 08:16

1 Answers1

0

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
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • Thank you for the code. Though it doesn't exactly fit my purpose it gave me some good pointers and know how on the python programming. Could you please explain the long list comprehension command that you had provided above? – s73 Feb 09 '18 at 06:26