Husam Saleh
Husam Saleh

Reputation: 35

Python dictionary key error

I am attempting to run a python program that can run a dictionary from a file with a list of words with each word given a score and standard deviation. My program looks like this:

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)

I have the word 'hunger' in my file but when I run this program to take 'hunger' and return its given score and std deviation, I get:

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

How is it that I get a key error even though 'hunger' is in the dictionary?

Upvotes: 0

Views: 4541

Answers (1)

mgilson
mgilson

Reputation: 310237

"hunger" isn't in the dictionary (that's what the KeyError tells you). The problem is probably your make_happiness_table function. I don't know if you've posted the full code or not, but it doesn't really matter. At the end of the function, you return an empty dictionary ({}) regardless of what else went on inside the function.

You probably want to open your file inside that function, create the dictionary and return it. For example, if your csv file is just 2 columns (separated by a comma), you could do:

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

Upvotes: 1

Related Questions