
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If Multiple Keys Exist in a Dictionary in Python
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
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
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
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