# Check if given multiple keys exist in a dictionary in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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
print("All keys are present")
else:
print("All keys are not present")
# Check for new keys
check_keys={"Mon","Fri"}
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
print("All keys are present")
else:
print("All keys are not present")
# Check for new keys
check_keys=set(["Mon","Fri"])
print("All keys are not present")
All keys are present
All keys are not present