Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Check Whether a Specific Key Exists in a Dictionary

Python Check Whether a Specific Key Exists in a Dictionary

Document Object Reference Manual Python3 Examples

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:

   

print

(

f

"The key '{key_to_find}' exists in the dictionary."

)

else

:

   

print

(

f

"The key '{key_to_find}' does not exist in the dictionary."

)

Code analysis:

Output result:

The key 'age' exists in the dictionary.

Document Object Reference Manual Python3 Examples