Use the Inbuilt keys() method to check if a key exists in dictionary Python. You can also use for in or has_key() method for it.
Example check is given Key already exists in a Python Dictionary
Simple example code. The key() method returns a list of all the available keys in the dictionary. Once get the list of keys then use the if statement and the ‘in’ operator to check if the key exists in the dictionary or not.
def check_key(dict1, key):
if key in dict1.keys():
print("Exists , ", end=" ")
print("value =", dict1[key])
else:
print("Not exists")
my_dict = {"A": 1, "B": 2, "C": 3}
check_key(my_dict, "A")
Output:
Another way of using if and in
def check_key(dict1, key):
if key in dict1:
print("Exists")
else:
print("Not exists ")
my_dict = {"A": 1, "B": 2, "C": 3}
check_key(my_dict, "A")
Output: Exists
Using the Inbuilt method has_key()
This method is used in older versions of Python.
def check_key(dict1, key):
if dict1.has_key(key):
print("Exists")
else:
print("Not exists ")
my_dict = {"A": 1, "B": 2, "C": 3}
check_key(my_dict, "A")
Output: It will throw an error.
AttributeError: ‘dict’ object has no attribute ‘has_key’
Do comment if you have any doubts or suggestions on this Python dictionary key code.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.