1

first of all im still learning python and im having a good time so far. while learning I ran into this issue I have a variable named MyList as follows

MyList = [{'orange', 'Lemon'},
 {'Apple', 'Banana', 'orange', 'Lemon'},
 {'Banana', 'Lemon'},
 {'Apple', 'orange'}]

I want to dump the list in a csv file in a rows as the same order as above so the csv will be like:

 orange   Lemon
 Apple    Banana   orange   Lemon 
 Banana   Lemon 
 Apple    orange 

so I put the command bellow

MyList.to_csv("MyList.csv", sep='\t', encoding='utf-8')

however it gives me the following error

AttributeError: 'list' object has no attribute 'to_csv'
ray
  • 63
  • 8

2 Answers2

1

You'll need to use the csv module and open a file for write:

import csv

MyList = [{'orange', 'Lemon'},
 {'Apple', 'Banana', 'orange', 'Lemon'},
 {'Banana', 'Lemon'},
 {'Apple', 'orange'}]

with open('MyList.csv', 'w') as f:
      
    # using csv.writer method from csv module
    write = csv.writer(f)
    write.writerows(MyList)
JNevill
  • 46,980
  • 4
  • 38
  • 63
1

You need to convert the list object into csv object.

import csv

with open('MyList.csv', 'w', newline='') as myfile:
     wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
     wr.writerows(MyList)

Refer the following question by Fortilan Create a .csv file with values from a Python list

Charitra Agarwal
  • 362
  • 1
  • 11