0

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?

Community
  • 1
  • 1
MEhsan
  • 2,184
  • 9
  • 27
  • 41

1 Answers1

2

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
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • This is working great, I am looking forward to replicate this functionality into a csv string instead of a csv file. What am I required to change here? – Saurabh Saxena Apr 29 '19 at 08:44