How to check if key exists in a dictionary in Python

Created
Modified

Using the in operator

In this method, we use the membership operator in. This operator is used to check if one value is a member of another. It returns a boolean value.

dict = {"GMT": 0, "BST": 1}
if "GMT" in dict:
  print("Exists")

# not in
if "gmt" not in dict:
  print("Does not exist")
Exists
Does not exist

However, remember the in operator is case sensitive hence you could either ensure all your keys are in the same case or you could use the upper() or lower() methods respectively.

Using the get Method

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

dict = {"GMT": 0, "BST": 1}
if dict.get("GMT") is not None:
  print("Exists")

if dict.get("gmt") is None:
  print("Does not exist")
Exists
Does not exist

Using EAFP

EAFP or ‘Easier to Ask for Forgiveness than Permission’ means holding an optimistic view for the code you are working on, and if an exception is thrown catch it and deal with it later.

dict = {"GMT": 0, "BST": 1}

try:
  v = dict["GMT"]
  # key exists in dict
except KeyError:
  # key doesn't exist in dict

Related Tags