richie
richie

Reputation: 18638

Write a list of dictionaries to csv where the dictionary values are lists

This is the code I have so far;

list_of_dict = [{'A': [1, 2, 3, 4, 5], 'B': [10, 11]}]
with open('result.csv','wb') as out:
    f1 = csv.DictWriter(out,list_of_dict[0].keys())
    f1.writeheader()
    f1.writerows(list_of_dict)

The output I get is;

     A            B
[1,2,3,4,5]    [10,11]

How do I get the output as;

A   B
1   10
2   11
3
4
5

Upvotes: 0

Views: 67

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122022

You'll have to transpose your one dictionary into a list of dictionaries, one for each row in the output:

import csv
from itertools import izip_longest

with open('result.csv','wb') as out:
    keys = list_of_dict[0].keys()
    f1 = csv.DictWriter(out, keys)
    f1.writeheader()
    f1.writerows(dict(zip(keys, row)) for row in izip_longest(*list_of_dict[0].values()))

Note that the keys are going to be listed in dictionary (arbitrary) order.

The above generator expression produces the dictionary per-row required:

>>> from itertools import izip_longest
>>> list_of_dict = [{'A': [1, 2, 3, 4, 5], 'B': [10, 11]}]
>>> keys = list_of_dict[0].keys()
>>> [dict(zip(keys, row)) for row in izip_longest(*list_of_dict[0].values())]
[{'A': 1, 'B': 10}, {'A': 2, 'B': 11}, {'A': 3, 'B': None}, {'A': 4, 'B': None}, {'A': 5, 'B': None}]

Upvotes: 1

Related Questions