【问题标题】:How to copy a csv file into a dictionary?如何将csv文件复制到字典中?
【发布时间】:2020-07-10 19:54:20
【问题描述】:

我正在研究 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 文件有多个列和行,带有一个标题,第一列表示人名。我不知道如何执行此操作,稍后我需要访问例如AliceAATG 的值。

另外,我正在使用模块sys 来导入DictReaderreader

【问题讨论】:

  • 你有没有尝试和data_reader任何事情
  • 对于 csv 文件中的每一行,字典中都会有一个条目。键将是该行第一列的名称。该值将是从该行的剩余列创建的元组。这就是你的目标吗?
  • 字典值可以是元组、列表、子字典等容器——按照@Wilf 的建议做,将row[0] 设为键并将row[1] 放入row[3] 中并将其设为关联值。
  • @ScottHunter 我不知道那是什么...
  • 你想要这样的东西Live-Demo

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


【解决方案1】:

您可以随时尝试自己创建函数。

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

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.

【讨论】:

  • 你能解释一下你做了什么吗?
  • 我编辑了可能有助于理解的 cmets。基本上,我已将此 CSV 文件数据(以字符串形式给出)翻译成字典列表。第一行给了我键和其他人的值——我把每一行都保存为字典,然后将它附加到列表中。希望本文和版本能帮助您理解!
猜你喜欢
  • 2016-08-19
  • 2012-05-09
  • 1970-01-01
  • 2014-04-12
  • 1970-01-01
  • 2020-04-17
  • 1970-01-01
  • 1970-01-01
  • 2015-06-24
相关资源
最近更新 更多