Let’s get to know together several ways to check if a key exists in a Python dictionary.
There are many ways to check if key exists in dictionary in Python. Let’s get to know the most convenient ones.
Using if and in
The esiest way is just to use if and in to check if the key is present in the dictionary.
my_dictionary = {"key1": 1, "key2": 2} if "key1" in my_dictionary: print("key1 is included in my_dictionary") else: print("key1 is not included in my_dictionary")
Another way of using if and in
You can also write it shorter like that. One liner does the same thing and looks more professional.
my_dictionary = {"key1": 1, "key2": 2} my_message = "key exists" if 'key1' in my_dictionary else "key does not exist" print(my_message)
Using keys method
Similar way is to use if and in with keys method. It will check keys of your dictionary.
my_dictionary = {"key1": 1, "key2": 2} my_key="key1" if my_key in my_dictionary.keys(): print("Key exists") else: print("Key does not exist")
Way to check if both key and value exist in dictionary
Using items method you are able to do the same but for the pair of key and value.
my_dictionary = {"key1": 1, "key2": 2} if ("key1", 1) in my_dictionary.items(): print("Key and Value exists") else: print("Key value pair doesn't exist")