0

我正在研究 cs50 的 pset6、DNA,我想读取一个如下所示的 csv 文件:

name,AGATC,AATG,TATC
Alice,2,8,3
Bob,4,1,5
Charlie,3,2,5

但问题是字典只有一个键和一个值,所以我不知道如何构建它。我目前拥有的是这段代码:

import sys

with open(argv[1]) as data_file:
    data_reader = csv.DictReader(data_file)

而且,我的 csv 文件有多个列和行,有一个标题,第一列表示人名。我不知道如何做到这一点,稍后我将需要访问单个数量 say,Alice的值AATG

另外,我正在使用模块sys来导入DictReader以及reader

4

1 回答 1

0

您始终可以尝试自己创建函数。

你可以在这里使用我的代码:

def csv_to_dict(csv_file):
    key_list = [key for key in csv_file[:csv_file.index('\n')].split(',')] # save the keys
    data = {} # every dictionary
    info = [] # list of dicitionaries
    # for each line
    for line in csv_file[csv_file.index('\n') + 1:].split('\n'):
        count = 0 # this variable saves the key index in my key_list.
        # for each string before comma
        for value in line.split(','):
            data[key_list[count]] = value # for each key in key_list (which I've created before), I put the value. This is the way to set a dictionary values.
            count += 1
        info.append(data) # after updating my data (dictionary), I append it to my list.
        data = {} # I set the data dictionary to empty dictionary.
    print(info) # I print it.

### Be aware that this function prints a list of dictionaries.

于 2020-07-10T21:05:43.417 回答