简体   繁体   中英

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

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}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM