Check if a Key exists in a Python dictionary

This tutorial examines various methods for checking if a key exists in a Python dictionary. A dictionary in Python is an unordered collection of data values that serve as a mapping mechanism for storing and managing values. It consists of key-value pairs, where values are retrieved based on their corresponding keys. Dictionaries are widely used and are a fundamental data type in Python.

Now let’s look at the different ways you can check if a key exists in a dictionary in Python.

NOTE: The Python has_key method, has been deprecated and is not available in
Python 3.

Using the “in” Operator

The “in” operator in Python is used to check if a specified element is present in a sequence, such as a list, tuple, or dictionary.

Vehicle = {'1': "Bus", '2':"Truck", '3':"Car"}  
Key = "2"  
boolean_val = Key in Vehicle #This time it will return True as 2 is in key. 
print("Is 2 present in Vehicle keys? ", boolean_val)

In the above code example, the line boolean_val = Key in Vehicle uses the “in” operator to check if the string value stored in Key is one of the keys in the dictionary Vehicle. The “in” operator returns a Boolean value indicating whether the specified key is present in the dictionary or not. In this case, since the key “2” is present in Vehicle, the expression evaluates to True, and this value is stored in the variable boolean_val.

Is 2 present in Vehicle keys? True

You can further use this in  if-else the statement to do further work. Considers the following example.

Vehicle= dict.fromkeys([1,3,4])
for i in range (1,5):
    if i in Vehicle:
        Vehicle[i] = "Hi "
    else:
        print(i, " not in key")
print(Vehicle)
2  not in key
{1: 'Hi ', 3: 'Hi ', 4: 'Hi '}

Keep in mind that the in operator is case sensitive, so either make sure all the keys are the same case or use the higher() or lower() methods while finding the match.

Vehicle = {'ONE': "Bus", 'TWO':"Truck", 'THREE':"Car"}  
key = "two"  
key.upper() in Vehicle
True

Using the get() Method

The get() method delivers the value of the related key in a dictionary. If the key isn’t there, it either returns None or a default value (if one was supplied). We can pass a key to this method and see if it exists in the given Python dictionary.

Syntax of get()

dict.get(keyname, value)

Parameters

  • dict – is the name of the dictionary you intend to work with,
  • keyname – It’s the key name you want to search for.
  • value  – is an optional argument and takes a string that will be returned as it is if the key doesn’t exist. By default, it returns None if it fails to find the key.
Vehicle = {'one': "Bus", 'two':"Truck", 'three':"Car"}  
key = "five"  
print(Vehicle.get(key, "Not found") )
Not found

Using the Keys() method

The Keys() function and the in operator can be used to see if a key exists in a dictionary. The Keys()  method returns a list of keys in the dictionary, and the in statement checks whether the provided key is in the list. It returns True if the key exists; otherwise, it returns False. It works exactly like in operator. But if you need a list of keys, then this works. 

Vehicle = {'one': "Bus", 'two':"Truck", 'three':"Car"}  
key = "two"  
print("Is two present in Vehicle keys? ",key in Vehicle.keys())
Is two present in Vehicle keys?  True

Conclusion

That concludes this tutorial. I hope it was helpful to you. If you have any questions, please leave them in the comments section. I would be happy to help. Additionally, please check out our Python tutorials page, where we regularly post content for both beginners and advanced developers. You’re sure to find something interesting there.