Now, let's say we want to check if the key "name" exists in the dictionary.
The best way to do this is to simply use the in keyword.
This keyword will return True if the key exists in the dictionary, and False if it doesn't.
PYTHON
dictionary = {
"name": "John",
"age": 30,
"city": "New York"
}
key = "name"if key in dictionary:
print("Key exists in dictionary")
else:
print("Key does not exist in dictionary")
BASH
Key exists in dictionary
Alternatively, you can also set the output of the in keyword to a variable:
PYTHON
dictionary = {
"name": "John",
"age": 30,
"city": "New York"
}
key = "name"
key_exists = key in dictionary
print(key_exists)
BASH
True
Conclusion
In this post, we learned how to check if a key exists in a dictionary in Python.
Simply use the in keyword on a dictionary and pass it the key you want to check.
Thanks for reading!
To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!