How to check if a given Key already exist in a dictionary in Python?

Spread the love

Problem –

You want to check if a key already exist in a dictionary in python.

Solution –

To check whether a key exist in a dictionary or not, you can use the in operator.


In [1]: person = {'Name': 'Noah', 'Age': 25, 'Location': 'New York'}

In [2]: if 'Location' in person:
   ...:     print('It exists')
   ...:     
It exists

In [3]: if 'Profession' in person:
   ...:     print('It exists')
   ...: else:
   ...:     print('It does not exist')
   ...:     
It does not exist

Rating: 1 out of 5.

Leave a Reply