How to check if a key exists in a Python dictionary?
Published on Aug. 22, 2023, 12:17 p.m.
There are several ways to check if a key exists in a Python dictionary:
- Use the
in
operator:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
if 'key2' in my_dict:
# key exists
pass
else:
# key does not exist
pass
- Use the
get()
method:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
value = my_dict.get('key2')
if value is not None:
# key exists
pass
else:
# key does not exist
pass
- Use the
keys()
method:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
if 'key2' in my_dict.keys():
# key exists
pass
else:
# key does not exist
pass
- Use the
items()
method:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
for key, value in my_dict.items():
if key == 'key2':
# key exists
pass
else:
# key does not exist
pass
All of the above methods will help you determine whether a particular key exists in a Python dictionary.