How to check if a key-value pair is present in a dictionary?
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
You can check a tuple of the key, value against the dictionary's .items()
.
test = {'a': 1, 'b': 2}
print(('a', 1) in test.items())
>>> True