>>> x = { 'a' : 'b' , 'c' : 'd' }
>>>'a' and 'c' in x
True
>>>'a' and 'b' in x
False
>>>'b' and 'c' in x
True
If in <dict> checks for keys, how come the last one that looks up b returns true even if there is no such key b?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You want
'b' in x and 'c' in xYou’re misunderstanding how the
andoperator works (and you’ve got your operator precedence wrong).inhas a higher precedence thanand, so your expression is parsed as:which is the same as:
because
bool('b')is alwaysTruesince'b'is a non-empty string.Here is a table of operator precedence in python
Note that even if
andhad higher precedence thanin, you still wouldn’t be getting what you want because('b' and 'c') in xwould reduce down to'c' in xsince'b' and 'c'returns'c'.One way to rewrite your expression would be:
This is overkill for just 2 keys to check, but quickly becomes useful if you have more keys to check.
As a final comment, you’re probably trying to apply operator chaining (which is really neat). However, some operators don’t lend themselves to chaining very well (
inis one of them). Expressions like3 > 10 > 100 > 1000do work by some strange python black magic. In my experience, relational operators chain nicely (‘<‘,’>’,’==’,'<=’,’>=’) but most of the other operators don’t chain in a way that is intuitive. In general,is equivalent to: