close

How to check if a key-value pair is present in a dictionary?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to check if a key-value pair is present in a dictionary in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to check if a key-value pair is present in a dictionary?

  1. 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.

  2. 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.

Method 1

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

Method 2

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

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read