Skip to content Skip to sidebar Skip to footer

How To Write A Dictionary Of Lists To A Csv File?

I have this dictionary of lists that I want to write it in a CSV file: file2_Dict = {'id': ' ', 'gender': ['M', 'M'], 'name': ['Smith', 'John'], 'city': ['Omaha','Lincoln']} The

Solution 1:

You can pre-process the dictionary and replace "empty" values with empty lists. Then use itertools.izip_longest() instead of zip():

import csv
from itertools import izip_longest

file2_Dict =  {'id': ' ', 'gender': ['M', 'M'], 'name': ['Smith', 'John'], 'city': ['Omaha','Lincoln']}

# replace space string values with empty listsfor key, value in file2_Dict.items():
    if value == ' ':
        file2_Dict[key] = []

withopen("test.csv", "wb") as outfile:
   writer = csv.writer(outfile)
   writer.writerow(file2_Dict.keys())
   writer.writerows(izip_longest(*file2_Dict.values()))

Which would produce:

gender,city,id,name
M,Omaha,,Smith
M,Lincoln,,John

Post a Comment for "How To Write A Dictionary Of Lists To A Csv File?"