Categories
Python Answers

How to check if a given key already exists in a dictionary with Python?

Spread the love

Sometimes, we want to check if a given key already exists in a dictionary with Python.

In this article, we’ll look at how to check if a given key already exists in a dictionary with Python.

How to check if a given key already exists in a dictionary with Python?

To check if a given key already exists in a dictionary with Python, we can use the in operator.

For instance, we write

d = {"key1": 10, "key2": 23}

if "key1" in d:
    print("yes")

to check if key1 is a key in dict d.

Since key1 is in d, 'yes' will be printed.

Conclusion

To check if a given key already exists in a dictionary with Python, we can use the in operator.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *