Categories
Python Answers

How to creating a dictionary from a csv file with Python?

Spread the love

Sometimes, we want to creating a dictionary from a csv file with Python.

In this article, we’ll look at how to creating a dictionary from a csv file with Python.

How to creating a dictionary from a csv file with Python?

To creating a dictionary from a csv file with Python, we can use dictionary comprehension.

For instance, we write

import csv

with open("coors.csv", mode="r") as infile:
    reader = csv.reader(infile)
    mydict = {rows[0]: rows[1] for rows in reader}

to open the coors.csv file with open.

Then we call csv.reader to read the file.

And then we create the mydict dict with the first entry of each row as the keys and the 2nd entry of each row as the value.

Conclusion

To creating a dictionary from a csv file with Python, we can use dictionary comprehension.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *