【问题标题】:returning a dictionary and assigning keys and values from text file返回字典并从文本文件中分配键和值
【发布时间】:2020-11-25 02:34:31
【问题描述】:

我在尝试为字典分配键和值的行收到错误“列表索引超出范围”。我试图将第二行中的项目命名为键,将第一个项目命名为值。我正在导入的文本文件如下所示:

A0101 伤寒脑膜炎
A0102 伤寒伴心脏受累
A0103 伤寒肺炎
A0104 伤寒性关节炎

 def disease_to_code_dictionary() :
    
    infile = open("ICD10.txt","r")
    header_row = infile.readline() # skip the header row
    dictionary = {}
    for line in infile :
        cells = line.split("\t") # split by the tab character
        dictionary[cells[1]]=cells[0]
        if len(cells) >= 2 : # only if the line had a tab
            code = cells[0]
            disease = cells[1]
            disease = disease.lower() # lowercase
            disease = disease.replace("\"","") # remove all double quotes


    infile.close()

【问题讨论】:

  • 错误是"list index out of range",所以错误是索引大于列表。该线路是dictionary[cells[1]]=cells[0]。该列表是cells。索引是01。这能解释清楚吗?
  • 感谢您的回复。是的,没错。因此,由于我正在创建字典,因此我不确定在分配键和值时缺少什么。我认为 0 和 1 可以识别第 1 行和第 2 行中的项目。由于列表有多行,我是否必须包括不仅仅是 0 和 1?
  • 不,cells 不包含行。您应该使用调试器或至少print 变量值来查看发生了什么。试试print(line)print(cells)
  • 啊...我在字典[line[1]]=line[0] 行中用'line'替换了'cells'。我认为这就是问题所在。谢谢!

标签: python python-3.x dictionary key


【解决方案1】:

您必须在空格上拆分行,然后将索引 1 到列表末尾的所有项目作为键连接,然后将索引 0 作为值。

cell = line.strip("\n").split(" ")
dictionary[' '.join(cell[1:])] = cell[0]

我也在更新它以使用context manager 来处理文件读取。

def disease_to_code_dictionary():
    with open("ICD10.txt", "r") as infile:
        dictionary = {}
        for line in infile:
            cell = line.strip("\n").split(" ")
            dictionary[' '.join(cell[1:])] = cell[0]
    return dictionary

【讨论】:

    猜你喜欢
    • 2019-07-20
    • 2018-12-21
    • 2020-12-03
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    相关资源
    最近更新 更多