Omar
Omar

Reputation: 567

write a dictionary of different-length lists to a csv file

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?

Upvotes: 3

Views: 1741

Answers (1)

strubbly
strubbly

Reputation: 3477

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()))

Upvotes: 2

Related Questions