Python Check Whether a Specific Key Exists in a Dictionary
In Python, you can use the in keyword to check whether a specific key exists in a dictionary.
Example
my_dict
=
{
'name'
:
'Alice'
,
'age'
:
25
,
'city'
:
'New York'
}
key_to_find
=
'age'
if
key_to_find
in
my_dict:
(
f
"The key '{key_to_find}' exists in the dictionary."
)
else
:
(
f
"The key '{key_to_find}' does not exist in the dictionary."
)
Code analysis:
my_dictis a dictionary containing three key-value pairs.key_to_findis the key we want to look up.if key_to_find in my_dict:This line of code usesinkeyword to checkkey_to_findwhether it exists among the keys ofmy_dict.- If the key exists, the program prints a message that the key exists; if not, it prints a message that the key does not exist.
Output result:
The key 'age' exists in the dictionary.
Python3 Examples