【问题标题】:Python dictionary key errorPython字典键错误
【发布时间】:2012-10-18 14:07:52
【问题描述】:

我正在尝试运行一个 python 程序,该程序可以从一个文件中运行一个字典,其中包含一个单词列表,每个单词都有一个分数和标准差。我的程序如下所示:

theFile = open('word-happiness.csv', 'r')

theFile.close()



def make_happiness_table(filename):
   ''' make_happiness_table: string -> dict
       creates a dictionary of happiness scores from the given file '''

return {}


make_happiness_table("word-happiness.csv")

table = make_happiness_table("word-happiness.csv")
(score, stddev) = table['hunger']
print("the score for 'hunger' is %f" % score)

我的文件中有“饥饿”一词,但是当我运行该程序以获取“饥饿”并返回其给定分数和标准偏差时,我得到:

(score, stddev) = table['hunger']
KeyError: 'hunger'

即使字典中有“饥饿”,我怎么会得到一个关键错误?

【问题讨论】:

  • 你能发布 make_happiness_table 的完整代码吗?根据您所做的,您只需返回一个空字典...或者可能在此处更正您的代码,因为它看起来有点混乱(您将文件名传递给一个什么都不做的函数,而您之前打开该文件的方式。 ..)
  • 打印您的字典 (print(table)) 并检查其中的内容。我敢打赌它不在你的字典中(也许它在文件中),但如果这个基本数据结构有错误,那将是惊人的。
  • 那可能是我的问题。我希望字典包含 .csv 文件中具有给定分数和标准偏差的单词。我该怎么做才不是空字典?

标签: python dictionary filenames


【解决方案1】:

"hunger" 不在字典中(这是KeyError 告诉你的)。问题可能是您的make_happiness_table 函数。我不知道您是否发布了完整的代码,但这并不重要。在函数结束时,无论函数内部发生了什么,您都会返回一个空字典 ({})。

您可能希望在该函数中打开文件,创建字典并返回它。例如,如果您的 csv 文件只有 2 列(用逗号分隔),您可以这样做:

def make_happiness_table(filename):
    with open(filename) as f:
         d = dict( line.split(',') for line in f )
         #Alternative if you find it more easy to understand
         #d = {}
         #for line in f:
         #    key,value = line.split(',')
         #    d[key] = value
    return d

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多