In this tutorial, you will learn how to check if the dictionary has a key in Python. We have covered five methods to search single or multiple keys in a dictionary. A dictionary in Python stores data in key-value pairs.
During programming, you might encounter scenarios where you would have to fetch data from a dictionary based on a specific key. However, in an ideal world, you would not know whether a key exists in that dictionary or not.
This is where this tutorial will help you in understanding different ways to check if a key is present in a dictionary or not. Here is the overview of the methods. Please feel free to jump to any section based on your requirements and see the code in action.
Also Read: How to Convert Binary to Decimal in Python [5 Methods]
How to Check If Dictionary Has a Key in Python
In this tutorial, we will cover the following methods to check if a dictionary has a key or not.
Method 1: Using the dictionary.keys() method where the dictionary is the name of your Python dictionary.
Method 2: By using if and in statements.
Method 3: Python Get() method.
Method 4: Check multiple keys with all()
Method 5: Using has_key() Python function
Also Read: Python Program To Display Fibonacci Series Up To N Terms
Let’s now see each of these methods.
Method 1: Using dictionary.keys() method
The keys() method returns a view object which contains all the keys in that dictionary as a list. Its syntax is dictionary.keys(), where the dictionary is the dictionary’s name whose keys you want to fetch.
Code:
codeitbro = {'Programming': "A", 'Apps':"B", 'Gadgets':"C", 'Python':"D"} search_key_term = 'Python' if search_key_term in codeitbro.keys(): print("Key is present in the dictionary.\n") else: print("Key is not present in the dictionary.")
Output:
Key is present in the dictionary
Explanation:
In the above code, we are using the keys() function to check if the key, which is search_key_term (“Python”), is present in the codeitbro dictionary.
Also Read: How To Automate Google Search With Python
Method 2: Using IF and IN statements
Code:
codeitbro = {'Programming': "A", 'Apps':"B", 'Gadgets':"C", 'Python':"D"} search_key_term = 'Python' if search_key_term in codeitbro: print("Key is present in the dictionary.\n") else: print("Key is not present in the dictionary.")
Output:
Key is present in the dictionary.
Explanation:
Here we use if and in a statement to look for a specific key in the dictionary. If the key is available, it will print “Key is present in the dictionary”; otherwise, it will execute the print statement in the else block.
Also Read: 20 Best Python Development Companies [2022]
Method 3: Python Dictionary Get() Method
The get() Python function returns the value of an item in the dictionary with a specified key.
Syntax: dictionary.key(key_name, value)
get() Parameters:
- key_name: It is a required parameter, and it denotes the name of the key whose value you want to fetch.
- Value: It is an optional parameter, and it denotes the value to return if the specified key is not present in the dictionary. The default value is none.
Also Read: 10 Best Udemy Python Courses for Beginners
Code:
codeitbro = {'Programming': "A", 'Apps': "B", 'Gadgets': "C", 'Python': "D"} if codeitbro.get('Programming')!=None: print("Key is present in the dictionary.\n") else: print("Key is not present in the dictionary.")
Output:
Key is present in the dictionary.
Explanation: In this method, we use the get() method and the if statement to check if a specific key is present in the dictionary and display a message accordingly.
Also Read: 10 Best Udemy Python Courses for Beginners
Method 4: Check multiple keys with all()
Python all() function returns True if all the items in an iterable are true; otherwise, it returns false. Also, note that it will return true if the iterable object is empty.
Code:
codeitbro = {'Programming': "A", 'Apps': "B", 'Gadgets': "C", 'Python': "D"} search_key_term = "Apps" if all (key in codeitbro for key in ("Programming","Gadgets")): print("All keys are present in the dictionary") else: print("All keys are not present in the dictionary")
Output:
All keys are present in the dictionary
Also Read: 10 Best Python Frameworks for Web Development
Method 5: Using the has_key() method [Deprecated in Python 3]
Python has_key(key) function returns true if the specified key is present in the dictionary; otherwise, it returns false.
Code:
codeitbro = {'Programming': "A", 'Apps': "B", 'Gadgets': "C", 'Python': "D"} search_key_term = "Apps" if codeitbro.has_key(search_key_term): print("Key is present in the dictionary") else: print("Key is not present in the dictionary")
Output:
Traceback (most recent call last): File "/Users/codeitbro/Downloads/Python Code/print-tutorial.py", line 5, in <module> if codeitbro.has_key(search_key_term): AttributeError: 'dict' object has no attribute 'has_key'
Please note that this method doesn’t work for Python 3 or newer versions. So, if you are using an old Python version, you can use this method to check if keys are available in a dictionary.
Also Read: 15 Best Python Libraries for Data Science and Analysis
Wrapping Up
So these were some methods to check if dict has a key in Python. Based on your requirements, you can use any of these ways to fetch values of data items based on specific keys. We have also covered how you can check if multiple keys exist in a dictionary or not.
Stay tuned for more such Python tutorials, and subscribe to our push notifications to never miss an update.
Next Read:
- 10 Best Python Libraries for Image Processing
- How To Create Keylogger In Python
- Learn Python Online With These 12 Best Free Websites
- How To Make A Digital Clock In Python Using Tkinter
- Sending Emails Using Python With Image And PDF Attachments
- Working With Python 3 Lists | Learn By Examples
- How To Make A Simple Python 3 Calculator Using Functions
Hello Friends! I am Himanshu, a hobbyist programmer, tech enthusiast, and digital content creator.
With CodeItBro, my mission is to promote coding and help people from non-tech backgrounds to learn this modern-age skill!