Is there a smart pythonic way to check if there is an item (key,value) in a dict?
a={\'a\':1,\'b\':2,\'c\':3}
b={\'a\':1}
c={\'a\':2}
b in a:
--> True
c
Use the short circuiting property of and
. In this way if the left hand is false, then you will not get a KeyError
while checking for the value.
>>> a={'a':1,'b':2,'c':3}
>>> key,value = 'c',3 # Key and value present
>>> key in a and value == a[key]
True
>>> key,value = 'b',3 # value absent
>>> key in a and value == a[key]
False
>>> key,value = 'z',3 # Key absent
>>> key in a and value == a[key]
False