To Create a dictionary from a csv file:
- Approach 1:
import csv
reader = csv.reader(open('filename.csv', 'r'))
d = {}
for row in reader:
k, v = row
d[k] = v
- Import the CSV module.
- Open the CSV file in read mode using the open() function.
- Create a CSV reader object using the csv.reader() function.
- Create an empty dictionary to store the data.
- Iterate over the rows in the CSV file using a for loop.
- For each row, extract the key and value using the row[0] and row[1] indexes.
- Add the key-value pair to the dictionary using the k and v variables.
- Approach 2:
import csv
with open('coors.csv', mode='r') as infile:
reader = csv.reader(infile)
with open('coors_new.csv', mode='w') as outfile:
writer = csv.writer(outfile)
mydict = {rows[0]:rows[1] for rows in reader}
- Here, the code uses context manager to open, read and close the CSV files.
- The code creates a dictionary comprehension to convert the CSV data to a dictionary.
- Approach 3:
import csv
from collections import defaultdict
my_dict = defaultdict(list)
with open('filename.csv', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
for line in csv_reader:
for key, value in line.items():
my_dict[key].append(value)
- Using defaultdict avoids the need to check if the key exists and also append the value to the list.