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("has key1")

We have the d dictionary.

And we check if there’s an entry with key 'key1' by writing:

"key1" in d

Since this is True, we see 'has key1' logged.

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 *