Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Read .csv file with columns of varying length as dictionary in Python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'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"],
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading