在Python中读取具有不同长度列的.csv文件作为字典

9fkzdhlc  于 2023-06-19  发布在  Python
关注(0)|答案(3)|浏览(133)

如何在Python中读取具有不同长度列的.csv文件?我想从.csv文件创建一个字典,其中.csv列作为字典值列表。
我已经想出了如何将字典写入.csv文件,但我需要帮助阅读相同的文件。

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)

预期输出:

{'Class1': ['A', 'B'],
 'Class2': ['C', 'D', 'E', 'F', 'G', 'H', 'I'],
 'Class3': ['J', 'K', 'L', 'M', 'N']}
ztyzrc3y

ztyzrc3y1#

要读取CSV文件,我建议使用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)

图纸:

{
    "Class1": ["A", "B"],
    "Class2": ["C", "D", "E", "F", "G", "H", "I"],
    "Class3": ["J", "K", "L", "M", "N"],
}
xriantvc

xriantvc2#

正如Andrej所说,DictReader可能是一条路。我想出了一个稍微不同的方法:

in_dict = {}

with open('test.csv', 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        for key, val in row.items():
            if key not in in_dict.keys():
                in_dict[key] = []
            if row[key]:
                in_dict[key].append(val)
    f.close()

print(in_dict)
mccptt67

mccptt673#

您也可以使用json将dict写入文件,然后再读取。

from pprint import pprint
import json

out_dict = {
    'Class1':       ['A', 'B'],
    'Class2':       ['C', 'D', 'E', 'F', 'G', 'H', 'I'],
    'Class3':       ['J', 'K', 'L', 'M', 'N']}
   
j = json.dumps(out_dict)

with open('test01.json', 'w') as fout:
    fout.write(j)

with open('test01.json', 'r') as fin:
    in_dict = json.load(fin)

pprint(in_dict)

图纸:

{'Class1': ['A', 'B'],
 'Class2': ['C', 'D', 'E', 'F', 'G', 'H', 'I'],
 'Class3': ['J', 'K', 'L', 'M', 'N']}

相关问题