从字典中访问元素?python
我试图通过给元素变量来访问字典中的元素,这样我就可以在其他函数中使用它们,但它总是告诉我它没有定义 我正在使用的文件(mood.txt): 我的代码:从字典中访问元素?python,python,dictionary,Python,Dictionary,我试图通过给元素变量来访问字典中的元素,这样我就可以在其他函数中使用它们,但它总是告诉我它没有定义 我正在使用的文件(mood.txt): 我的代码: def theFile(): moodFile = open("mood.txt") theMood = moodFile.readlines() moodFile.close() return(theMood) def makeTheDict(myFile): moodDict = {} fo
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)
我不断地发现这个错误:
NameError: global name 'name' is not defined
我希望有人能向我解释我做错了什么!谢谢 您没有在函数中定义
名称。使用mooddit[mood]
编辑名称:
def printMood(mood, moodDict):
if mood in moodDict:
print("The people who are", mood, ":", moodDict[mood])
或者只需使用dict.get()
属性,该属性接受一个默认参数,以便在不存在键的情况下返回。这使您能够了解if
条件以及每次迭代中的比较:
def printMood(mood, moodDict):
print("The people who are", mood, ":", moodDict.get(mood, '-')) # you can use any default string instead of '-'.
我猜这句话就是问题所在:
if mood in moodDict:
print("The people who are", mood, ":", name)
尝试:
你还没有发布你的实际代码,因为如果你发布了,你会在这里得到一个错误,关于未定义的行(情绪,名称)=行。拆分(“,”
很抱歉,当我试图键入并同时查看它时,一定出了问题。好的,我知道我做了什么!!我修好了谢谢你!现在这就更有意义了!
if mood in moodDict:
print("The people who are", mood, ":", name)
if mood, names in moodDict.iteritems():
print("The people who are", mood, ":", names)