【问题标题】:How can I create a nested dictionary containing info. from csv file如何创建包含信息的嵌套字典。来自 csv 文件
【发布时间】:2020-07-11 13:57:45
【问题描述】:

我正在研究 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 到字典中添加所有值,以便我有一个以后可以访问的数据库。

【问题讨论】:

  • 没有像"Alice" 这样的动态键名,而是有"name":"Alice"

标签: python python-3.x dictionary nested cs50


【解决方案1】:

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

【讨论】:

  • 我有一个问题。这个数据库只是AGATC,其他三个只是一个小数据库。有没有一种方法可以让我遍历字典而不是硬编码它应该是什么?谢谢!
  • record 以上是 csv 行的 OrderedDict(字典类型)。只需从中删除 name 键(以及不需要在数据中的任何其他键)就足够了。 (更新了答案)
  • 可以使用name = record.pop('name') 代替name = record["name"],它会从字典中删除该键/值对(并返回该键的值)。
【解决方案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'}}

【讨论】:

  • 嘿!你能解释一下这是做什么的吗:line = next(data_file) hdr = line.rstrip().split(',') # file header@DarryIg
  • @NicolasFuchs - 添加了更多 cmets 以进一步澄清。如果有其他问题,请告诉我。
  • 好的,谢谢!我也不明白这行的语法...但是我会搜索这些运算符的含义
  • @NicolasFuchs--哪一行的语法?如果你指出它可能只需要一点时间来解释?是词典理解线吗?
猜你喜欢
  • 1970-01-01
  • 2022-11-05
  • 2023-03-15
  • 1970-01-01
  • 2017-07-25
  • 2014-09-20
  • 2021-12-08
  • 2021-02-20
  • 2015-12-11
相关资源
最近更新 更多