Load CSV data into List and Dictionary using Python
Last Updated :
13 Sep, 2022
Prerequisites: Working with csv files in Python
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format. CSV raw data is not utilizable in order to use that in our Python program it can be more beneficial if we could read and separate commas and store them in a data structure. We can convert data into lists or dictionaries or a combination of both either by using functions csv.reader and csv.dictreader or manually directly and in this article, we will see it with the help of code.
Example 1: Loading CSV to list
CSV File:
Load CSV data into List and Dictionary
Python3
import csv
filename = "Geeks.csv"
with open (filename, 'r' ) as data:
for line in csv.reader(data):
print (line)
|
Output:
Load CSV data into List and Dictionary
Example 2: Loading CSV to dictionary
Python3
import csv
filename = "Geeks.csv"
with open (filename, 'r' ) as data:
for line in csv.DictReader(data):
print (line)
|
Output:
Load CSV data into List and Dictionary
Example 3: Loading CSV into list of Dictionaries
Python3
from csv import DictReader
with open ( "geeks.csv" , 'r' ) as f:
dict_reader = DictReader(f)
list_of_dict = list (dict_reader)
print (list_of_dict)
|
Output:
Load CSV data into List and Dictionary
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...