MEhsan
MEhsan

Reputation: 2324

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 problem is that not all the keys of the dictionary have a list of items as a value. In this case the key (i.e.'id') has a string as value (i.e. " "). I tried to use the solution provided by Tim Pietzcker, but this only outputs the header of the csv file (keys of the dictionary), like this:

id, gender, name, city

The expected output should be, like this:

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

Any idea how to solve this problem?

Upvotes: 0

Views: 1261

Answers (1)

alecxe
alecxe

Reputation: 474191

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 lists
for key, value in file2_Dict.items():
    if value == ' ':
        file2_Dict[key] = []

with open("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

Upvotes: 2

Related Questions