naraemee naraemee - 9 days ago 5
Python Question

Accessing elements from a dictionary? Python

I am trying to access elements from a dictionary by giving them variables so that I can use them in other functions, but it keeps tell me that it is not defined.

The file I am using (mood.txt):

happy, Jennifer Clause
happy, Jake Foster
sad, Jonathan Bower
mad, Penny
excited, Logan
awkward, Mason Tyme


my code:

def theFile():
moodFile = open("mood.txt")
theMood = moodFile.readlines()
moodFile.close()
return(theMood)

def makeTheDict(myFile):
moodDict = {}

for lines in myFile:
(mood, name) = lines.split(",")

moodDict[mood] = name.strip()

return(moodDict)


def printMood(mood, moodDict):

if mood in moodDict:
print("The people who are", mood, ":", name)


def main():

moodFile = theFile()

moodDict = makeTheDict(moodFile)

findMood = input("Which mood do you want to choose?: ")
printMood(findMood, moodDict)


I keep getting this error:

NameError: global name 'name' is not defined


I hope someone can explain to me what I'm doing wrong! Thanks!

Answer

You didn't define the name in your function. use moodDict[mood] to ge the name:

def printMood(mood, moodDict):
    if mood in moodDict:
        print("The people who are", mood, ":", moodDict[mood])

Or just use dict.get() attribute which accepts a default argument to return in case of not existing the key. Which makes you get ride of if condition and the comparison in each iteration:

def printMood(mood, moodDict):
    print("The people who are", mood, ":", moodDict.get(mood, '-')) #  you can use any default string instead of '-'.
Comments