如何创建包含信息的嵌套字典。从csv文件

2024-09-29 02:25:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究cs50的pset6,DNA,我想读一个csv文件,看起来像这样:

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

我要创建的是一个嵌套字典,如下所示:

data_dict = {
  "Alice" : {
    "AGATC" : 2,
    "AATG" : 8,
    "TATC" : 3
  },
  "Bob" : {
    "AGATC" : 4,
    "AATG" : 1,
    "TATC" : 5
  },
  "Charlie" : {
    "AGATC" : 3,
    "AATG" : 2,
    "TATC" : 5
  }
}

所以我想用这个:

with open(argv[1]) as data_file:
    for i in data_file:

(或另一个变体)循环通过csv文件和append到字典,添加所有值,这样我就有了一个以后可以访问的数据库


Tags: 文件csvnamedata字典dnafilebob
2条回答

使用简单的文件读取

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'}}

您应该使用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)

相关问题 更多 >