Load CSV data into List and Dictionary using Python


Introduction

The CSV file format is a well-liked one for exchanging data between computers. A number of libraries are built into the versatile and adaptable programming language Python that can read and write CSV files. Lists and dictionaries are two of the most popular Python data structures, and they are excellent for storing CSV data for further processing and analysis.

This article will walk you through the process of using Python to load CSV data into lists and dictionaries, using real-world examples to make the process easier to understand.

Loading CSV Data into a Python List

The csv module that comes with Python allows users to read from and write to CSV files. We'll use a fictitious CSV file called data.csv to demonstrate how to load CSV data into a list. It contains the following information:

Name, Age, Country
Alice, 25, USA
Bob, 30, UK
Charlie, 35, Canada

Let's look at how to add this CSV data to a list:

import csv

with open('data.csv', 'r') as file:
   reader = csv.reader(file)
   data_list = list(reader)
    
print(data_list)

This script reads the CSV data and converts it into a list of lists, where each sub-list corresponds to a row in the CSV file:

[['Name', 'Age', 'Country'], ['Alice', '25', 'USA'], ['Bob', '30', 'UK'], ['Charlie', '35', 'Canada']]

Loading CSV Data into a Python Dictionary

Python dictionaries can offer a more organised and adaptable approach to store CSV data. The csv.DictReader object, which considers each row as an ordered dictionary mapping with a header, is used to import CSV data into a dictionary.

We should load our data.adding a csv file to a dictionary

import csv

with open('data.csv', 'r') as file:
   reader = csv.DictReader(file)
   data_dict = [row for row in reader]

print(data_dict)

When this script is run, a list of dictionaries is produced, each of which corresponds to a row in the CSV file.:

[{'Name': 'Alice', 'Age': '25', 'Country': 'USA'}, {'Name': 'Bob', 'Age': '30', 'Country': 'UK'}, {'Name': 'Charlie', 'Age': '35', 'Country': 'Canada'}]

Here, the dictionary's remaining entries serve as the matching values while the CSV headers (Name, Age, and Country) serve as the dictionary's keys.

Advantages of Using Lists and Dictionaries for CSV Data

An easy way to store and manage the data is by loading CSV data into lists or dictionaries. You could, for example, apply a function to each data entry or loop over the list or dictionary to retrieve specific data entries.

Additionally, using dictionaries can provide additional benefits. For some usage circumstances, the key-value pairing can be a more logical approach to access data. For instance, you can immediately retrieve the second person's "Country" from the data_dict as follows:

print(data_dict[1]['Country'])  # Prints 'UK'

Conclusion

The built-in csv module in Python makes working with CSV files simple. Whether you decide to store your CSV data in a list or a dictionary mostly relies on the type of data you have and how you intend to work with and utilise it. In contrast to dictionaries, which offer a structured and flexible approach and map keys to values for easy data access, lists are straightforward and offer an ordered collection of items.

It's essential to comprehend these CSV data handling techniques if you want to use Python to analyse and process data. You can successfully select the optimal approach for your unique use case through real implementation and analysis, resulting in the creation of legible and efficient code. These abilities will surely be useful whether you're working on data analysis, machine learning, or web scraping.

Updated on: 18-Jul-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements