89DEVs

Python: How to check if dict contains key?

How to check if a dictionary contains a key? Use the 'in' operator.


myDict = {'a':1, 'b':2, 'c':3}
'a' in myDict


True is returned, because myDict contains 'a'.

True

To reverse the result, use the 'not in' operator.


myDict = {'a':1, 'b':2, 'c':3}
'a' not in myDict


False is returned, because it is False that 'a' is not in myDict.

False

If we test for a key that is not in myDict, True is returned.


myDict = {'a':1, 'b':2, 'c':3}
'd' not in myDict


True

Use the result of the 'in' operator in an if/else statement.


myDict = {'a':1, 'b':2, 'c':3}
if 'a' in myDict:
   print('a is in myDict')
else:
   print('a is not in myDict')


a is in myDict

In Python 2 dictionaries had a has_key() method. This has been removed in Python 3, therefore use the 'in' operator instead.