How do I read in a .csv file in Python with columns of varying lengths? I want to create a dictionary from the .csv file, with the .csv columns as lists of dictionary values.
I’ve figured out how to write the dictionary to a .csv file, but I need help reading in that same file.
import csv
import itertools
path = 'C:/Users/.../test.csv'
out_dict = {
'Class1': ['A', 'B'],
'Class2': ['C', 'D', 'E', 'F', 'G', 'H', 'I'],
'Class3': ['J', 'K', 'L', 'M', 'N']}
# write dictionary to csv
with open(path, 'wt', newline='') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(out_dict.keys())
writer.writerows(itertools.zip_longest(*out_dict.values()))
csv_file.close()
# read csv as dictionary
with open(path, 'rt') as csv_file:
reader = csv.reader(csv_file);
in_dict = ???
csv_file.close()
print(in_dict)
Desired Output:
{'Class1': ['A', 'B'],
'Class2': ['C', 'D', 'E', 'F', 'G', 'H', 'I'],
'Class3': ['J', 'K', 'L', 'M', 'N']}
>Solution :
To read the CSV file back I recommend to use csv.DictReader:
import csv
import itertools
path = '<PATH>'
out_dict = {
"Class1": ["A", "B"],
"Class2": ["C", "D", "E", "F", "G", "H", "I"],
"Class3": ["J", "K", "L", "M", "N"],
}
# write dictionary to csv
with open(path, 'wt', newline='') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(out_dict.keys())
writer.writerows(itertools.zip_longest(*out_dict.values()))
# read csv as dictionary
out = {}
with open(path, 'rt') as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
for k, v in row.items():
if v != '':
out.setdefault(k, []).append(v)
print(out)
Prints:
{
"Class1": ["A", "B"],
"Class2": ["C", "D", "E", "F", "G", "H", "I"],
"Class3": ["J", "K", "L", "M", "N"],
}