MuradE MuradE -4 years ago 66
Python Question

combining for loops and if statements with dictionaries in python

I am working on an exercise in which I'm supposed to have both a list and dictionary and to print out a specified message if the value in the list is not in the dictionary can someone please help? For some reason, it only prints out the else statement, but not the if. I am sure I'm missing something

poll_takers = ['angel', 'jana', 'murad', 'adel', 'joe', 'jake']

favorite_language = {
'angel': 'python',
'jana': 'c++',
'murad': 'python',
'adel': 'swift',
}

for name in poll_takers:
if name == favorite_language:
print(name.title() + ", thank you for taking the poll.")
else:
print(name.title() + ", please take the poll.")

Answer Source

your conditional should be

if name in favorite_language

which checks if a key is in the dictionary, otherwise

if name == favorite_language

always evaluates to false since the string name isnt equal to the dictionary, since == tests for equality, that's why the else statement keeps getting triggered

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download