Menu Close

How to create a dictionary from a CSV file?

Sometimes, we want to create a dictionary from a CSV file.

In this article, we’ll look at how to create a dictionary from a CSV file.

How to create a dictionary from a CSV file?

To create a dictionary from a CSV file, we can use the csv.DictReader class.

For instance, we write:

import csv

reader = csv.DictReader(open("foo.csv"))
for row in reader:
    print(row)

to read the foo.csv file with open.

Then we use the returned file as the argument for csv.DictReader to convert the rows to dictionaries.

Next, we loop through the reader iterator with a for loop.

In the loop body, we print the row value, which are dictionaries of each row.

If foo.csv is:

foo,bar
1,2
3,4
5,6

Then the for loop prints:

{'foo': '1', 'bar': '2'}
{'foo': '3', 'bar': '4'}
{'foo': '5', 'bar': '6'}

Conclusion

To create a dictionary from a CSV file, we can use the csv.DictReader class.

Posted in Python, Python Answers