How do I make a proper csv file using DictWriter method

Viewed 78

How do I make a 3 or more column csv file using the example?

import csv

fruits = ["apple", "banana", "grape", "orange"]
vegetables = ["onion", "garlic", "carrot", "cabbage"]
spices = ["salt", "pepper", "paprika", "cumin"]

types = ["Fruits", "Vegetables", "Spices"]

with open("test.csv", "w") as testfile:
  writer = csv.DictWriter(testfile, fieldnames=types)
  
  writer.writeheader()

I'm pretty confused on the DictWriter method and would like some help on how to properly make a csv file with 3 or more columns. So far the best I could do was:

Fruits,Vegetables,Spices
orange,,
,cabbage,
,,cumin

something like this, which is pretty bad.

3 Answers

Since you have all lists, it would be easier to use csv.writer instead of Dictwriter:

In [182]: with open('test.csv', 'w', newline='') as csvfile:
     ...:     writer = csv.writer(csvfile)
     ...:     writer.writerow(types)
     ...:     writer.writerows(zip(fruits, vegetables, spices))
     ...: 

Output:

Fruits,Vegetables,Spices
apple,onion,salt
banana,garlic,pepper
grape,carrot,paprika
orange,cabbage,cumin

Use pandas:

import pandas as pd

fruits = ["apple", "banana", "grape", "orange"]
vegetables = ["onion", "garlic", "carrot", "cabbage"]
spices = ["salt", "pepper", "paprika", "cumin"]
types = ["Fruits", "Vegetables", "Spices"]

df = pd.DataFrame( list(zip(fruits,vegetables,spices)), columns = types) 
df.to_csv(r'file_name.csv', index = False)

Result:

Fruits,Vegetables,Spices
apple,onion,salt
banana,garlic,pepper
grape,carrot,paprika
orange,cabbage,cumin

One possibility using DictWriter and zip:

with open("test.csv", "w") as testfile:
    writer = csv.DictWriter(testfile, fieldnames=types)
    writer.writeheader()
    for row in zip(fruits, vegetables, spices):
        writer.writerow(dict(zip(types, row))
Related