Home > Article > Backend Development > How to Create a Python Dictionary from a CSV File?
Creating a Dictionary from a CSV File
When working with a CSV file, it is often useful to create a dictionary for quick and easy access to data. A dictionary can store key-value pairs, where the keys are unique and the values are associated with those keys.
This guide will explore how to create a dictionary from a CSV file using Python. The CSV file should have unique keys in the first column and associated values in the second column.
To begin, open the CSV file using the 'open' function with the 'r' mode for reading. Use the 'csv.reader' function to create a reader object that will iterate over the rows in the file.
import csv with open('coors.csv', mode='r') as infile: reader = csv.reader(infile)
To create the dictionary, use a dictionary comprehension. This comprehension will iterate over each row in the reader object and create a key-value pair from the first and second columns, respectively.
mydict = {rows[0]:rows[1] for rows in reader}
This line creates a dictionary where the keys are the unique values from the first column and the values are the associated values from the second column.
print(mydict)
Finally, print the dictionary to see its contents. This will display the key-value pairs in the dictionary.
The above is the detailed content of How to Create a Python Dictionary from a CSV File?. For more information, please follow other related articles on the PHP Chinese website!