【发布时间】:2021-01-28 07:25:00
【问题描述】:
我正在尝试读取 csv 文件(实际上是 tsv,但 nvm)并将其设置为字典,其中其键是所述 csv 的列名,其余行是这些键的值。 我还有一些用“#”字符标记的 cmets,我打算忽略它们:
csv_in.csv
##Some comments
##Can ignore these lines
Location Form Range <-- This would be the header
North Dodecahedron Limited <---|
East Toroidal polyhedron Flexible <------ These lines would be lists
South Icosidodecahedron Limited <---|
主要思想是像这样存储它们:
final_dict = {'Location': ['North','East','South'],
'Form': ['Dodecahedron','Toroidal polyhedron','Icosidodecahedron'],
'Range': ['Limited','Flexible','Limited']}
到目前为止,我可以像这样接近:
tryercode.py
import csv
dct = {}
# Open csv file
with open(tsvfile) as file_in:
# Open reader instance with tab delimeter
reader = csv.reader(file_in, delimiter='\t')
# Iterate through rows
for row in reader:
# First I skip those rows that start with '#'
if row[0].startswith('#'):
pass
elif row[0].startswith('L'):
# Here I try to keep the first row that starts with the letter 'L' in a separate list
# and insert this first row values as keys with empty lists inside
dictkeys_list = []
for i in range(len(row)):
dictkeys_list.append(row[i])
dct[row[i]] = []
else:
# Insert each row indexes as values by the quantity of rows
print('¿?')
到目前为止,字典的骨架看起来还不错:
print(dct)
{'Location': [], 'Form': [], 'Range': []}
但到目前为止,我尝试的所有操作都未能按照预期的方式将值附加到键的空列表中。只能对第一行这样做。
(...)
else:
# Insert each row indexes as values by the quantity of rows
print('¿?')
for j in range(len(row)):
dct[dictkeys_list[j]] = row[j] # Here I indicate the intented key of the dict through the preoviously list of key names
我在stackoverflow上进行了广泛搜索,但找不到这种方式(代码模板的灵感来自this post的答案,但字典的结构不同。
【问题讨论】:
-
最后一行使用
dct[dictkeys_list[j]].append(row[j])
标签: python csv dictionary