Computer >> Computer tutorials >  >> Programming >> Python

How to check if a given key already exists in a Python dictionary?


The membership operator in can also be used with dictionary object

>>> d1={1:'aaa',2:'bbb',3:"ccc",4:'ddd',5:'eee'}
>>> 3 in d1
True
>>> 9 in d1
False

Additionally, keys() method returns a view object of keys in dictionary. Membership operator in also tells you if key is present

>>> 3 in d1.keys()
True