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.