CSV to List in Python
Python is a very powerful language that also allows us to read and make use of tabular datasets and spreadsheets in the program code.
Python supports features through which we can convert a CSV file format dataset into a Python list. This can be done by importing a module named CSV, let’s have a look on the example and see how to jump from CSV to a Python list
Note: In the example below I am using the dataset with 10 fruits and their color
import csv with open('fruit.csv') as f: reader = csv.reader(f) my_list = list(reader) print("csv to list:",my_list)
csv to list : [['Fruit_name', 'Fruit_colour'], ['Apple', 'red/green'], ['Orange', 'orange'], ['Cherry', 'red/green'], ['Chikoo', 'brown'], ['Banana', 'yellow'], ['Strawberry', 'red/pink'], ['Custerdapple', 'green'], ['Watermellon', 'green'], ['Mango', 'yellow/green']]
In the example above we have imported the CSV module to read a CSV file named ‘fruit’ which has 10 columns with different fruits and their colors. We have simply assigned a variable ‘my_list’ and used the ‘list’ function to convert the CSV file into Python list. The returned output gives different list with column names and their values embedded into a list.
You may also read: