Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Initialize an Empty Dictionary in Python
Next article icon

Python | Check if given multiple keys exist in a dictionary

Last Updated : 27 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

A dictionary in Python consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value.

Input : dict[] = {“geeksforgeeks” : 1, “practice” : 2, “contribute” :3} keys[] = {“geeksforgeeks”, “practice”} Output : Yes Input : dict[] = {“geeksforgeeks” : 1, “practice” : 2, “contribute” :3} keys[] = {“geeksforgeeks”, “ide”} Output : No

Let’s discuss various ways of checking multiple keys in a dictionary : 

Method #1 Using comparison operator : This is the common method where we make a set which contains keys that use to compare and using comparison operator we check if that key present in our dictionary or not. 

Python3




# Python3 code to check multiple key existence
# using comparison operator
 
# initializing a dictionary
sports = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3}
 
# using comparison operator
print(sports.keys() >= {"geeksforgeeks", "practice"})
print(sports.keys() >= {"contribute", "ide"})
 
 
Output:
True False

Time complexity: O(k), where k is the number of keys in the dictionary
Auxiliary space: O(k), to create the set of keys for comparison.

Method #2 Using issubset() : In this method, we will check the keys that we have to compare is subset() of keys in our dictionary or not. 

Python3




# Python3 code heck multiple key existence
# using issubset
 
# initializing a dictionary
sports = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3}
 
# creating set of keys that we want to compare
s1 = set(['geeksforgeeks', 'practice'])
s2 = set(['geeksforgeeks', 'ide'])
 
print(s1.issubset(sports.keys()))
print(s2.issubset(sports.keys()))
 
 
Output:
True False

Time complexity: O(n), where n is the length of the test_keys list.
Auxiliary space: O(n), as we are creating a dictionary with n key-value pairs.

Method #3 Using if and all statement : In this method we will check that if all the key elements that we want to compare are present in our dictionary or not . 

Python3




# Python3 code check multiple key existence
# using if and all
 
# initializing a dictionary
sports = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3}
 
# using if, all statement
if all(key in sports for key in ('geeksforgeeks', 'practice')):
    print("keys are present")
else:
    print("keys are not present")
 
# using if, all statement
if all(key in sports for key in ('geeksforgeeks', 'ide')):
    print("keys are present")
else:
    print("keys are not present")
 
 
Output:
keys are present keys are not present

Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in dictionary.

Method #4 : Alternatively, you can use a list comprehension and list comparison to achieve a similar result:

Python3




# initializing a dictionary
sports = {"geeksforgeeks": 1, "practice": 2, "contribute": 3}
 
# using a list comprehension to check multiple key existence
keys_to_check1 = ['geeksforgeeks', 'practice']
keys_to_check2 = ['geeksforgeeks', 'ide']
keys_present1 = [key for key in keys_to_check1 if key in sports]
keys_present2 = [key for key in keys_to_check2 if key in sports]
print(keys_present1 == keys_to_check1)
print(keys_present2 == keys_to_check2)
# This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
True False

Time complexity: O(n),
Auxiliary Space: O(n) and, since it involves a single pass through the list of keys to check. It uses a list comprehension to generate a list of keys that are present in the dictionary.



Next Article
Initialize an Empty Dictionary in Python
author
raghvendra3499
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • How to Check if a Key Exists in a Dictionary in TypeScript ?
    In TypeScript dictionaries are used whenever the data is needed to be stored in key and value form. We often retrieve the data from the dictionaries using an associated key. Therefore it becomes crucial to check whether the key exists in a dictionary or not. We can use the below methods to check if
    4 min read
  • Python - How to Check if a file or directory exists
    Sometimes it's necessary to verify whether a dictionary or file exists. This is because you might want to make sure the file is available before loading it, or you might want to prevent overwriting an already-existing file. In this tutorial, we will cover an important concept of file handling in Pyt
    5 min read
  • Initialize an Empty Dictionary in Python
    To initialize an empty dictionary in Python, we need to create a data structure that allows us to store key-value pairs. Different ways to create an Empty Dictionary are: Use of { } symbolUse of dict() built-in functionInitialize a dictionaryUse of { } symbolWe can create an empty dictionary object
    3 min read
  • Count dictionaries in a list in Python
    A list in Python may have items of different types. Sometimes, while working with data, we can have a problem in which we need to find the count of dictionaries in particular list. This can have application in data domains including web development and Machine Learning. Lets discuss certain ways in
    5 min read
  • Python - Find dictionary keys present in a Strings List
    Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the extraction of dictionary keys from strings list feeded. This problem can have application in many domains including data. Lets discuss certain ways in which this task can be performed. Method #1: U
    7 min read
  • Handling missing keys in Python dictionaries
    In Python, dictionaries are containers that map one key to its value with access time complexity to be O(1). But in many applications, the user doesn't know all the keys present in the dictionaries. In such instances, if the user tries to access a missing key, an error is popped indicating missing k
    4 min read
  • Add new keys to a dictionary in Python
    In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples: Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=). [GFGTABS] Python d = {"a": 1, "b": 2} d["c"]
    2 min read
  • How to Add Duplicate Keys in Dictionary - Python
    In Python, dictionaries are used to store key-value pairs. However, dictionaries do not support duplicate keys. In this article, we will explore several techniques to store multiple values for a single dictionary key. Understanding Dictionary Key ConstraintsIn Python, dictionary keys must be unique.
    3 min read
  • Check if element exists in list in Python
    In this article, we will explore various methods to check if element exists in list in Python. The simplest way to check for the presence of an element in a list is using the in Keyword. Example: [GFGTABS] Python a = [10, 20, 30, 40, 50] # Check if 30 exists in the list if 30 in a: print("Eleme
    3 min read
  • Python - Access Dictionary items
    A dictionary in Python is a useful way to store data in pairs, where each key is connected to a value. To access an item in the dictionary, refer to its key name inside square brackets. Example: [GFGTABS] Python a = {"Geeks": 3, "for": 2, "geeks": 1} #Access the value a
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences