22.4 C
New York
Sunday, November 24, 2024
HomeAppsHow to Check If Dict Has Key in Python

How to Check If Dict Has Key in Python [5 Methods]

In this tutorial, you will learn how to check if a dictionary has key in Python using key(), all(), get(), and has_key() methods. Learn here.

In this tutorial, you will learn how to check if the dictionary has a key in Python. We have covered five methods to search for 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.

This is where this tutorial will help you understand different ways to check if a key is present in a dictionary or not.

Here is an overview of the methods. Please feel free to jump to any section based on your requirements and see the code in action.

Also ReadHow to Convert Binary to Decimal in Python [5 Methods]

How to Check If Dictionary Has a Key in Python

check if dict has key in python

This tutorial will cover the following methods to check whether a dictionary has a key.

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

Let’s now see each of these methods.

Method 1: Using the dictionary.keys() method

The keys() method returns a view object that 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 ReadHow 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.

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: An optional parameter denotes the value to return if the specified key is not present in the dictionary. The default value is none.

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.

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

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'

This method doesn’t work for Python 3 or newer versions. So, if you use an old Python version, you can use this method to check if keys are available in a dictionary.

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 checking whether multiple keys exist in a dictionary.

Stay tuned for more such Python tutorials, and subscribe to our push notifications to never miss an update.

Himanshu Tyagi
Himanshu Tyagi
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!
RELATED ARTICLES