Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python字典键错误_Python_Dictionary_Filenames - Fatal编程技术网

Python字典键错误

Python字典键错误,python,dictionary,filenames,Python,Dictionary,Filenames,我正在尝试运行一个python程序,该程序可以从一个包含单词列表的文件中运行字典,每个单词都有一个分数和标准差。我的程序如下所示: theFile = open('word-happiness.csv', 'r') theFile.close() def make_happiness_table(filename): ''' make_happiness_table: string -> dict creates a dictionary of happines

我正在尝试运行一个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)
我的文件中有“饥饿”一词,但当我运行此程序获取“饥饿”并返回其给定分数和std偏差时,我得到:

(score, stddev) = table['hunger']
KeyError: 'hunger'
即使“饥饿”在字典里,我怎么会得到一个键错误?

“饥饿”
不在字典里(这就是
键错误
告诉你的)。问题可能是您的
make\u happiness\u table
功能。我不知道你是否发布了完整的代码,但这并不重要。在函数结束时,返回一个空字典(
{}
),而不管函数中发生了什么

您可能希望在该函数中打开文件,创建字典并返回它。例如,如果csv文件只有两列(用逗号分隔),则可以执行以下操作:

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

你能帮我写下“制造幸福”表的完整代码吗?根据您所做的,您只需返回一个空的dict。。。或者在这里更正您的代码,因为它看起来有点混乱(您将一个文件名传递给一个不执行任何操作的函数,而您以前是以这种方式打开该文件的…)打印您的字典(
print(table)
)并检查其中的内容。我打赌它不在你的字典里(可能在文件里),但是如果这个基本的数据结构有一个bug,那将是令人惊讶的。那可能是我的问题。我希望字典由.csv文件中的单词组成,并带有给定的分数和标准偏差。我如何才能做到这一点,使它不是一本空字典?