How to Read CSV Data in Dictionary Format Using DictReader - Quick Python Tutorial

preview_player
Показать описание
How do you read a .csv file into a dictionary in python?

In this Quick Python Tutorial, we are going to learn how to read a CSV file in Python and load the data records as dictionaries using the DictReader class from the Python csv module.

In this video, we are going to learn how to load the contents of a csv file as dictionaries in Python.

We have a csv file here, the first line contains the header, which has the names of all the columns, followed by the data in the next lines. And in the Python file, we import the csv module, and in a with statement, we open the csv file by passing the path to the file as a string. And then we pass an empty string to the newline parameter. This helps to prevent problems that may lead to empty records caused by extra lines in some documents (some documents end with both \r\n) . And then we use the as keyword to give our csv resource a name.

To load the contents of the csv file in dictionary format, we use a DictReader object. We pass the csv resource to the constructor and we assign the result to a variable. The DictReader object will read the csv resource and map each row to a dictionary. And since our csv file has a header that contains the field names, then these names will be used as the keys for the dictionaries.

And then we can use a for loop to iterate through all of the rows in the csv resource.

#Python #CSV #DictReader
Рекомендации по теме
Комментарии
Автор

wonderful video it's help me to resolve a big problem thansk!

juandavidsanchezvargas