Javatpoint Logo
Javatpoint Logo

How to Check if a Key Exists in a Python Dictionary

In Python, a dictionary is an unordered set of data values that can be used to manage and store values like a map. Unlike other Data Types, which can only carry a specific value as an item, Dictionary can hold a key-value pair. The dictionary includes a key-value pair to make it more efficient. Polymorphism is not allowed in dictionary keys. A Dictionary is built in Python by enclosing a succession of entries in curly braces and separating them with a comma. The Dictionary stores couples of values, one of which is the Key & the other is the Key:value pair element.

In a dictionary, values can be of any data structure and can even be replicated, but keys cannot be copied that must be immutable.

Checking a Key in Dictionary

In Python, a dictionary is indeed a useful data structure that stores key-value pairs. Getting the value of a specific key from a dictionary is frequently required in programming; however, the existence of a particular key in the dictionary is not really guaranteed always. As a result, it's a good idea to double-check whether a key belongs to the dictionary before retrieving its value.

Using has_key()

If a given key is found in the dictionary, the has_key() method returns true; else, it returns false.

Python 3 has made this deprecated. This method can be used if we are running on an older version than Python 3.

The command below can be used to confirm the Python version in cmd.

Code:

Output:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [37], in ()
      1 Animals = {'1': "Cat", '2':"Rat", '3':"Bat"}
      2 key_to_check_for = '2'
----> 3 if Animals.has_key(key_to_check_for):
      4   print("Key exists in Animals")
      5 else:

AttributeError: 'dict' object has no attribute 'has_key'

Since this code was executed on Python 3 it is showing an error.

if-in Statement

This method checks whether a particular key exists inside the dictionary using the if-in statement. We employ the membership operator in, in this manner. This operator is used to determine if one value belongs to another. It gives you a boolean result.

Code:

Output:

Key exists in Animals

Now, looking at the negative case.

Code:

Output:

There is no key "4" in Animals

Likewise, the not in operator could be used to see if a key in a dictionary does not exist. However, keep in mind that the in operation is case sensitive, so either make sure all the keys are the same case or use the higher() or lower() methods.

Code:

Output:

Key exists in Animals

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 the get() function is:

Here, dict name is the title of the dictionary you'll be using.

Parameters

  1. Keyname- The value's keyname that you want to return.
  2. value- If the key does not exist, this value is supplied as an option.

Code:

Output:

Key exists in Animals

Now taking a negative case,

Code:

Output:

There is no key "5" in Animals

When utilizing this method, please Keep this in mind that if we do have a key with that value None, it will not be accurate. If we don't have one, this technique will suffice. If we want to use the values returned by this method, we can save them in a variable.

Using Keys()

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 "if, in" statement checks whether the provided key is in the list. It returns True if the key exists; otherwise, it returns False.

Input

Output:

Key exists in Animals

Check to see if the Dictionary has Multiple Keys.

In one statement, we can also check if the dictionary contains multiple keys. We can use the all() function in combination with the list comprehension to see if the dictionary contains many or all keys.

Code:

Output:

Not all the keys are there in Animals

Examine the List of Dictionaries to see if the Key Exists

A list of dictionaries is a collection of dictionaries that can be found in a list.

  • list_of_dictionary - a list with three dictionary objects in it.
  • "b" in keys for the keys in the list of dictionary - producing the list of keys within list of dictionaries using list comprehension. Then, on the list, see if one is available. It will return a list with True for keys that are "b" and False for keys that are not one.
  • any() - Verifies the True/False list provided by list comprehension. The key "b" is present in the dictionary list if it includes at least one True. The "if" block is then executed after it returns True. Otherwise, the "else" block is executed.

Code:

Output:

Key exists in list_of_dictionaries

Check if the Key is in the JSON Dictionary

JSON stands for "Javascript Object Notation", and it is a key-value pair that saves values.

The json.loads() method can be used to construct a dictionary from a JSON text.

Then, as seen below, we can use the "if and in" to see if the key is present in the JSON dictionary.

Input

Output:

Key is present in the JASON dictionary

Conclusion

To recap, we have learnt how to check if the key is in the dictionary using several ways. We have also learnt how to apply those methods to various instances in order to see if the key is in the dictionary. We have also seen how each option takes a different amount of time.


Next Topic#





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA