Check if given multiple keys exist in a dictionary in Python

PythonServer Side ProgrammingProgramming

During data analysis using python, we may need to verify if a couple of values exist as keys in a dictionary. So that the next part of the analysis can only be used with the keys that are part of the given values. In this article we will see how this can be achieved.

With Comparison operators

The values to be checked are put into a set. Then the content of the set is compared with the set of keys of the dictionary. The >= symbol indicates all the keys from the dictionary are present in the given set of values.

Example

 Live Demo

Adict = {"Mon":3, "Tue":11,"Wed":6,"Thu":9}
check_keys={"Tue","Thu"}

# Use comaprision
if(Adict.keys()) >= check_keys:
   print("All keys are present")
else:
   print("All keys are not present")
# Check for new keys
check_keys={"Mon","Fri"}
if(Adict.keys()) >= check_keys:
   print("All keys are present")
else:
   print("All keys are not present")

Output

Running the above code gives us the following result −

All keys are present
All keys are not present

With all

In this approach we use for loops to check every value to be present in the dictionary. The all function returns true only if all the values form the check key set is present in the given dictionary.

Example

 Live Demo

Adict = {"Mon":3, "Tue":11,"Wed":6,"Thu":9}
check_keys={"Tue","Thu"}

# Use all
if all(key in Adict for key in check_keys):
   print("All keys are present")
else:
   print("All keys are not present")
# Check for new keys
check_keys={"Mon","Fri"}
if all(key in Adict for key in check_keys):
   print("All keys are present")
else:
   print("All keys are not present")

Output

Running the above code gives us the following result −

All keys are present
All keys are not present

With subset

In this approach we take the values to be searched as a set and validate if it is a subset of the keys from the dictionary. For this we use the issubset function.

Example

 Live Demo

Adict = {"Mon":3, "Tue":11,"Wed":6,"Thu":9}
check_keys=set(["Tue","Thu"])

# Use all
if (check_keys.issubset(Adict.keys())):
   print("All keys are present")
else:
   print("All keys are not present")
# Check for new keys
check_keys=set(["Mon","Fri"])
if (check_keys.issubset(Adict.keys())):
   print("All keys are present")
else:
   print("All keys are not present")

Output

Running the above code gives us the following result −

All keys are present
All keys are not present
raja
Published on 13-May-2020 14:25:31
Advertisements