Load CSV data into List and Dictionary using Python

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:



python-load-csv

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing module 
import csv
   
# csv fileused id Geeks.csv
filename="Geeks.csv"
  
# opening the file using "with"
# statement
with open(filename,'r') as data:
   for line in csv.reader(data):
            print(line)
          
# then data is read line by line 
# using csv.reader the printed 
# result will be in a list format 
# which is easy to interpret

chevron_right


Output:

python-load-csv-to-list

Example 2: Loading CSV to dictionary

filter_none

edit
close

play_arrow

link
brightness_4
code

import csv
  
  
filename ="Geeks.csv"
  
# opening the file using "with" 
# statement
with open(filename, 'r') as data:
      
    for line in csv.DictReader(data):
        print(line)

chevron_right


Output:

python-csv-to-dictionary

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.