2

Here it is asked how to dump a list of dictionaries (with matching keys) into a csv file.

My question is similar, however I assume that the dictionaries have not necessarily matching keys: in which case I would like to leave that cell with no value (or assign None/0/..). Example below.

  • Is there an utility into the csv module that allow me to do this?
  • In the affirmative case, how do I do it?
  • In the negative case, should I collect all the keys and then go through all the dictionaries and set the value of the missing key to None/0/...?

Example

to_csv = [{'name':'bob','age':25,'weight':200, 'height':181},
          {'name':'jim','age':31,'weight':180}]

Should become:

name,age,weight,height
bob,25,200,181
jim,31,180,None
Community
  • 1
  • 1
rafforaffo
  • 511
  • 2
  • 7
  • 21

1 Answers1

7
import csv

to_csv = [{'name':'bob','age':25,'weight':200, 'height':181},
          {'name':'jim','age':31,'weight':180}]

# find header
s = set()
for i in to_csv:
    s.update(i)
header = list(s)

with open("foo.csv", 'w') as f:
    writer = csv.writer(f)
    writer.writerow(header)
    for d in to_csv:
        writer.writerow([d.get(i, "None") for i in header])
pacholik
  • 8,607
  • 9
  • 43
  • 55