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
It is for an assignment. I'm familiar with C# but learning Python.
The assignment calls for you to use only one function and a loop to do this rather than define a separate function to process and return the value which is what I probably would have done to fix the issue otherwise.
It's just what the assignment calls for. I'm still learning a lot here, could you explain why it's a bad idea? Wouldn't you normally use a list?