3

I am trying to write a dictionary of lists to a csv file. The solution in:Write dictionary of lists to a CSV file

will trim longer lists. For example if I want to write the following:

d = {"key1": [1, 2, 3], "key2": [4, 5, 6], "key3": [7, 8, 9, 11]}
with open("test.csv", "wb") as outfile:
writer = csv.writer(outfile)
writer.writerow(d.keys())
writer.writerows(zip(*d.values()))

The results is

key3   key2  key1
7      4     1
8      5    2
9      6    3

11 is deleted from key3. Any ideas?

Community
  • 1
  • 1
Omar
  • 557
  • 2
  • 6
  • 23

1 Answers1

2

The quick and easy answer is to use itertools.izip_longest instead of zip

import itertools
import csv

d = {"key1": [1, 2, 3], "key2": [4, 5, 6], "key3": [7, 8, 9, 11]}
with open("test.csv", "wb") as outfile:
    writer = csv.writer(outfile)
    writer.writerow(d.keys())
    writer.writerows(itertools.izip_longest(*d.values()))
strubbly
  • 3,347
  • 3
  • 24
  • 36