0

I tried to check values of a dictionary within a for loop with an if statement that has multiple conditions.

First I tried this code which didn't work:

d = {2312: 'Jim', 2323: 'Anna', 2314: 'Tim', 3054: 'Marc', 3574: 'Valerie', 3698: 'Nina'}

Smith = list()
Miller = list()

for name in d.values():
    if name == 'Jim' or 'Anna' or 'Tim':
        Smith.append(name)
    else:
        Miller.append(name)

print(Smith)
print(Miller)

Then I tried this which worked:

d = {2312: 'Jim', 2323: 'Anna', 2314: 'Tim', 3054: 'Marc', 3574: 'Valerie', 3698: 'Nina'}

Smith = list()
Miller = list()

for name in d.values():
    if name == 'Jim' or name == 'Anna' or name == 'Tim':
        Smith.append(name)
    else:
        Miller.append(name)

print(Smith)
print(Miller)

My question is why does the first one not work but the second code does?

And is there a 'easier' code to check this?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
PoPhoRmA
  • 23
  • 5
  • 5
    This answers your questions: [Why does "a == x or y or z" always evaluate to True?](https://stackoverflow.com/questions/20002503/why-does-a-x-or-y-or-z-always-evaluate-to-true) – mkrieger1 Oct 21 '21 at 15:15
  • 2
    To answer your second question, "is there an easier way", yes! `if name in ("Jim", "Anna", "Tim")` – ddejohn Oct 21 '21 at 15:18

0 Answers0