2 回答
TA贡献1818条经验 获得超11个赞
你应该使用 python 的csv.DictReader模块
import csv
data_dict = {}
with open(argv[1]) as data_file:
reader = csv.DictReader(data_file)
for record in reader:
# `record` is a OrderedDict (type of dict) of column-name & value.
# Instead of creating the data pair as below:
# ```
# name = record["name"]
# data = {
# "AGATC": record["AGATC"],
# "AATG": record["AATG"],
# "TATC": record["TATC"],
# ...
# }
# data_dict[name] = data
# ```
# you can just delete the `name` column from `record`
name = record["name"]
del record["name"]
data_dict[name] = record
print(data_dict)
TA贡献1809条经验 获得超8个赞
使用简单的文件读取
with open(argv[1], 'r') as data_file:
line = next(data_file) # get the first line from file (i.e. header)
hdr = line.rstrip().split(',') # convert header string to comma delimited list
# ['name', 'AGATC', 'AATG', 'TATC']
data_dic = {}
for line in data_file:
line = line.rstrip().split(',')
# name and dictionary for current line
data_dic[line[0]] = {k:v for k, v in zip(hdr[1:], line[1:])}
print(data_dic)
输出
{'Alice': {'AATG': '8', 'AGATC': '2', 'TATC': '3'},
'Bob': {'AATG': '1', 'AGATC': '4', 'TATC': '5'},
'Charlie': {'AATG': '2', 'AGATC': '3', 'TATC': '5'}}
添加回答
举报