naraemee naraemee - 3 months ago 17
Python Question

print all elements of a dictionary? Python

I can't seem to figure out how to print all elements of a dictionary! I keep getting errors saying 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()

def makeTheDict(myFile):
moodDict = {}

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

moodDict[mood] = name.strip()


def printMood(mood, moodDict):

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

def allMoods(moodDict):

#code I am having trouble with
for moods in moodDict:
print(mood, moodDict[moods])

def main():

moodFile = theFile()

moodDict = makeTheDict(moodFile)

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


I am trying to print all the moods inside the function
. Whenever I remove mood from
print(mood, moodDict[moods])
, it prints out all the names fine, but when I insert the mood it says it is not defined.

I tried calling
printMood(mood, moodDict)
but I couldn't get that to work either!

How do I print out everyones moods with their name? Can anyone help! Thanks!


You had moods and mood in this routine. You need just one of them. mood seems best.

def allMoods(moodDict):
    for mood in moodDict:
        print(mood, moodDict[mood])

With that change, everything works. It works now because you have defined mood in the for loop, where previously you were calling on mood, but had never defined or set it to anything.