How To Import A CSV Into A Dictionary Python

One of the most common tasks in Python is reading and processing data from a CSV (Comma Separated Values) file.

CSV files are simple text files that contain data in a tabular format, where each row consists of one or more fields separated by commas. In this tutorial, we will demonstrate how you can import a CSV file into a dictionary using Python programming language.

By following this guide, you will be able to read data from a CSV file and store it in a dictionary that can be manipulated and processed as required.

Step 1: Prepare a CSV file

First, we need to create a sample CSV file to work with. You can prepare your own CSV file or use the following example:

ID,Name,Age,Occupation
1,John,35,Software Developer
2,Jane,31,Data Analyst
3,Michael,42,Network Administrator
4,Alice,29,Web Developer

This CSV file represents a table with four columns (ID, Name, Age, and Occupation). Each row contains information about a particular person.

Save this file as “example.csv” in your working directory.

Step 2: Write a function to import the CSV file into a dictionary

To read the CSV file and store the data in a dictionary, we will use the built-in csv module in Python. This module provides functionality to read from and write to CSV files. We will create a function called read_csv_file that takes the filename as input and returns a dictionary containing the data from the file.

In this function, we first import the csv module. We then open the file using the with statement and create a DictReader object that reads the CSV file’s contents. The DictReader object creates a dictionary for each row and returns these dictionaries in a list.

Step 3: Call the function and display the imported data

Now you can call the read_csv_file function to import the CSV file into a dictionary. After that, the dictionary can be displayed as output. In the following code, we call the read_csv_file function, passing the “example.csv” filename as a parameter, and store the returned dictionary in a variable called “csv_data”.

Full Code

Output

{'ID': '1', 'Name': 'John', 'Age': '35', 'Occupation': 'Software Developer'}
{'ID': '2', 'Name': 'Jane', 'Age': '31', 'Occupation': 'Data Analyst'}
{'ID': '3', 'Name': 'Michael', 'Age': '42', 'Occupation': 'Network Administrator'}
{'ID': '4', 'Name': 'Alice', 'Age': '29', 'Occupation': 'Web Developer'}

As you can see, the output is a list of dictionaries representing the rows of the CSV file.

Conclusion

In this tutorial, we have shown you how to import a CSV file into a dictionary using Python. By utilizing the csv module, you can easily process and manipulate data stored in CSV files.