-1

I have dictionary like this (key:[array]):

{'person1@mail.com': ['BMW', 'Dodge'],'person2@mail.com': ['Mercedes']}

and I would like to print this to CSV and make one column for each element of an array, so the result should like (header is optionable):

Owner,Car_1,Car_2
person1@gmail.com, BMW, Dodge
person2@gmail.com, Mercedes

Thanks!

skutik
  • 101
  • 1
  • 2
  • 8

2 Answers2

1

Use python csv module.

import csv

d = {'person1@mail.com': ['BMW', 'Dodge'],'person2@mail.com': ['Mercedes']}

with open('Cars.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',')
    spamwriter.writerow(['Owner', 'Car_1', 'Car_2'])
    for k, v in d.items():
        spamwriter.writerow([k] + v)

enter image description here

Rahul
  • 8,599
  • 4
  • 42
  • 78
  • I used the same as in my example: d={'person1@mail.com': ['BMW', 'Dodge'],'person2@mail.com': ['Mercedes']} – skutik Jul 19 '17 at 08:54
  • The code snippet that I posted gives the result shown in pic for python3.5. – Rahul Jul 19 '17 at 08:58
1

You can use csv.writer, assuming your data is stored in dictionary d

import csv

with open('output.csv', 'w') as fp:
    writer = csv.writer(fp)
    writer.writerow(['Owner','Car_1','Car_2'])
    for key, val in d.items():
        writer.writerow([key] + val)
taras
  • 5,216
  • 9
  • 32
  • 41