0

beginner question here:

I want to check if certain keys in a dict have a certain value

simplified version of what I tried:

d = {'a':'b', 'b':'b', 'c':'c'}

def b_check():
    if d['a'] and d['b'] and d['c'] == 'b':
        return True
    else:
        return False

However, I always get True as the output.

Thanks in advance for the help :)

Felix
  • 123
  • 1
  • 1
  • 5
  • `d['a'] == d['b'] == d['c'] == 'b'`. – Willem Van Onsem Aug 26 '17 at 22:50
  • okay thanks so this was super simple :), why doesn't the 'and' version work though? – Felix Aug 26 '17 at 22:53
  • because and checks the *truthiness* of its operands: it checks whether `d['a']` is `True`. A non-empty string is considered to be `True`. So now it checks the second operand `d['b']` which is non-empty as well, so `True` again. The final operand is `d['c'] == 'b'` which holds, so the three elements are all `True`. – Willem Van Onsem Aug 26 '17 at 22:55
  • Thanks for the initial answer and the quick explanation!!! – Felix Aug 26 '17 at 23:01

0 Answers0