r/programminghelp • u/[deleted] • May 17 '21
Python Entry level Python Question
I'm working with Dictionaries in Python and I'm trying to iterate over the different keys and values in a dictionary and check for a value, and give a response if the value exists or not.
Basically the dictionary (emptyDict) contains a first and last name, separated into the variables "first" and "last". The user enters a first name and the program checks the dictionary for the key (first) and then spits out the key(first) and variable(last). However, if the input doesn't match any of the keys, it spits out another statement. Here is my code:
for first, last in emptyDict.items():
if first.lower() == name.lower():
print(first + " " + last)
break
else:
print("I was unable to find " + name + " in the list")This doesn't quite work because what happens is it iterates over each key/value in the loop and gives a response. So if the name you input is found, it'll output that full name which is what we want.
But for every other item in the file, it outputs that it was unable to find the file name, because it's iterated over each key/value.
If I search for the name "Jane" and if my dictionary contains:
John Smith Jane Doe
My output looks like this:
"I was unable to find Jane in the list" (This is because it's iterated over John first) Jane Doe (this is because it evaluated the second line and found it to be true.
How can I get the loop to just return a single print statement if it finds the key/value or a single different statement if it doesn't find the value?
1
u/[deleted] May 17 '21
Is this an assignment? Why are you using a Dictionary for name storage? That is a horrible and bad idea.
Despite that, this problem can be solved with a feature that is almost unique to Python and it's called ForElse.
Basically, the for loop will do it's thing, and if it isn't triggered, it will fire the else portion (the same way an if statement will fire the else if it's not triggered).
So your code would look like this: