Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Check if a Key Exists in a Python Dictionary
Next article icon

Check if a Key Exists in a Python Dictionary

Last Updated : 05 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Python dictionary can not contain duplicate keys, so it is very crucial to check if a key is already present in the dictionary. If you accidentally assign a duplicate key value, the new value will overwrite the old one.

To check if given Key exists in dictionary, you can use either in operator or get() method. Both are easy are use and work efficiently.

Using IN operator

Python
# Example dictionary d = {'a': 1, 'b': 2, 'c': 3}  # Key to check key = 'b' print(key in d)  # Output: True  key = 'g' print(key in d)  # Output: False 

Output
True False 

So in a given dictionary, our task is to check if the given key already exists in a dictionary or not.

Different Methods to Check If a Key Exists in a Dictionary

There can be different ways to check whether a given key Exists in a Dictionary, we have covered the following approaches:

Check If the Key Exists Using keys() Method

keys() method returns a list of all the available keys in the dictionary. With the Inbuilt method keys(), use the if statement with the 'in' operator to check if the key is present in the dictionary or not. 

Python
# Python3 Program to check whether a # given key already exists in a dictionary.  def checkKey(dic, key):     if key in dic.keys():         print("Present, ", end =" ")         print("value =", dic[key])     else:         print("Not present")          # Driver Code dic = {'a': 100, 'b':200, 'c':300} key = 'b' checkKey(dic, key)  key = 'w' checkKey(dic, key) 

Output
Present,  value = 200 Not present 

Check If the Key Exists Using get() Method

The Inbuilt method get() returns a list of available keys in the dictionary. With keys(), use the if statement to check whether the key is present in the dictionary. If the key is present it will print "Present" otherwise it will print "Not Present".

Python
d = {'a': 100, 'b':200, 'c':300}  # check if "b" is none or not. if d.get('b') == None:   print("Not Present") else:   print("Present") 

Output
Present 

Handling ‘KeyError’ Exception while accessing dictionary

Use try and except to handle the KeyError exception to determine if a key is present in a diet. The KeyError exception is generated if the key you're attempting to access is not in the dictionary.

Python
d = {'Aman': 110, 'Rajesh': 440, 'Suraj': 990}  try:     d["Kamal"]     print('Found') except KeyError as error:     print("Not Found") 



Next Article
Check if a Key Exists in a Python Dictionary

S

Smitha Dinesh Semwal
Improve
Article Tags :
  • Python
  • Python Programs
  • python-dict
  • Python dictionary-programs
Practice Tags :
  • python
  • python-dict

Similar Reads

    Check If a Nested Key Exists in a Dictionary in Python
    Dictionaries are a versatile and commonly used data structure in Python, allowing developers to store and retrieve data using key-value pairs. Often, dictionaries may have nested structures, where a key points to another dictionary or a list, creating a hierarchical relationship. In such cases, it b
    3 min read
    Check if Tuple Exists as Dictionary Key - Python
    The task is to check if a tuple exists as a key in a dictionary. In Python, dictionaries use hash tables which provide an efficient way to check for the presence of a key. The goal is to verify if a given tuple is present as a key in the dictionary.For example, given a dictionary d = {(3, 4): 'gfg',
    3 min read
    Check if Value Exists in Python Dictionary
    We are given a dictionary and our task is to check whether a specific value exists in it or not. For example, if we have d = {'a': 1, 'b': 2, 'c': 3} and we want to check if the value 2 exists, the output should be True. Let's explore different ways to perform this check in Python.Naive ApproachThis
    2 min read
    Check and Update Existing Key in Python Dictionary
    The task of checking and updating an existing key in a Python dictionary involves verifying whether a key exists in the dictionary and then modifying its value if it does. If the key is found, its value can be updated to a new value, if the key is not found, an alternative action can be taken, such
    4 min read
    Check if dictionary is empty in Python
    Sometimes, we need to check if a particular dictionary is empty or not. Python# initializing empty dictionary d = {} print(bool(d)) print(not bool(d)) d = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print(bool(d)) print(not bool(d)) OutputFalse True True False Different Methods to Check if a Dictionary is Em
    5 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