简体   繁体   中英

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 (ie 'id' ) has a string as value (ie " " ). 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?

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

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