Python | Check if key has Non-None value in dictionary
Last Updated :
17 Apr, 2023
Sometimes, while working with Python dictionaries, we might come across a problem in which we need to find if a particular key of the dictionary is valid i.e it is not False or has a non-none value. This kind of problem can occur in the Machine Learning domain. Let’s discuss certain ways in which this problem can be solved.
Method #1: Using if
This task can simply be solved using the conditional operator “if”. The if statement autochecks for the truthness of any statement and hence with the key’s value.
Python3
test_dict = { 'gfg' : None , 'is' : 4 , 'for' : 2 , 'CS' : 10 }
print ( "The original dictionary : " + str (test_dict))
res = False
if test_dict[ 'gfg' ]:
res = True
print ( "Does gfg have a Non-None value? : " + str (res))
|
Output
The original dictionary : {'gfg': None, 'is': 4, 'for': 2, 'CS': 10}
Does gfg have a Non-None value? : False
Time Complexity: O(1)
Auxiliary Space: O(1)
Method #2: Using bool() + get()
The above functions together can be used to perform this particular task. The get performs the task of getting the value corresponding a key and bool function checks for truthfulness.
Python3
test_dict = { 'gfg' : None , 'is' : 4 , 'for' : 2 , 'CS' : 10 }
print ( "The original dictionary : " + str (test_dict))
res = bool (test_dict.get( 'gfg' ))
print ( "Does gfg have a Non-None value? : " + str (res))
|
Output
The original dictionary : {'gfg': None, 'is': 4, 'for': 2, 'CS': 10}
Does gfg have a Non-None value? : False
Time complexity:
The get() method has an average time complexity of O(1) and a worst-case time complexity of O(n) where n is the size of the dictionary.
The bool() function has a constant time complexity of O(1).
Therefore, the time complexity of the code is O(1).
Auxiliary space complexity:
The code uses constant auxiliary space to store the dictionary and a few variables.
Therefore, the auxiliary space complexity of the code is O(1).
Method 3: using the in keyword and a ternary operator:
- Initialize a dictionary test_dict with key-value pairs. In this dictionary, the key ‘gfg’ has a None value, and the other keys have some integer values.
- Print the original dictionary using the print() function.
- Using a ternary operator, check if the key ‘gfg’ is present in the dictionary test_dict and if its value is not None.
- a. If the condition is True, set the value of res to True.
- b. If the condition is False, set the value of res to False.
- Print the result of the check using the print() function.
Python3
test_dict = { 'gfg' : None , 'is' : 4 , 'for' : 2 , 'CS' : 10 }
print ( "The original dictionary : " + str (test_dict))
res = True if 'gfg' in test_dict and test_dict[ 'gfg' ] is not None else False
print ( "Does gfg have a Non-None value? : " + str (res))
|
Output
The original dictionary : {'gfg': None, 'is': 4, 'for': 2, 'CS': 10}
Does gfg have a Non-None value? : False
Time complexity: O(1) since dictionary lookups are constant time in python.
Auxiliary Space: O(1) since we only use constant additional memory.
Method 4: using the “try-except” block to check if the key has a non-None value in the dictionary:
Approach:
- Initialize the dictionary with key-value pairs.
- Print the original dictionary.
- Use the “try-except” block to check if the ‘gfg’ key has a non-None value.
- If the key is present and has a non-None value, set the res variable to True, else set it to False.
- If the key is not present in the dictionary, set the res variable to False.
- Print the result.
Python3
test_dict = { 'gfg' : None , 'is' : 4 , 'for' : 2 , 'CS' : 10 }
print ( "The original dictionary : " + str (test_dict))
try :
if test_dict[ 'gfg' ] is not None :
res = True
else :
res = False
except KeyError:
res = False
print ( "Does gfg have a Non-None value? : " + str (res))
|
Output
The original dictionary : {'gfg': None, 'is': 4, 'for': 2, 'CS': 10}
Does gfg have a Non-None value? : False
Time complexity: O(1) since dictionary lookup is a constant time operation.
Auxiliary space: O(1) since the space used by the variables is constant irrespective of the size of the dictionary.
Method #5: Using the dictionary’s get() method with a default value
Here’s the step-by-step approach:
- Initialize the dictionary.
- Print the original dictionary.
- Use the dictionary’s get() method with a default value of None to check if the key has a non-None value.
- If the value returned by get() is not None, set the result to True, else False.
- Print the result.
Python3
test_dict = { 'gfg' : None , 'is' : 4 , 'for' : 2 , 'CS' : 10 }
print ( "The original dictionary : " + str (test_dict))
res = True if test_dict.get( 'gfg' , None ) is not None else False
print ( "Does gfg have a Non-None value? : " + str (res))
|
Output
The original dictionary : {'gfg': None, 'is': 4, 'for': 2, 'CS': 10}
Does gfg have a Non-None value? : False
Time complexity: O(1)
Auxiliary space: O(1)
Method #6: Using the “in” keyword with a direct comparison to None value.
Approach:
- Initialize the dictionary.
- Print the original dictionary.
- Check if a key has a Non-None value in the dictionary using the “in” keyword.
- Store the result in a boolean variable.
- Print the result.
Example:
Python3
test_dict = { 'gfg' : None , 'is' : 4 , 'for' : 2 , 'CS' : 10 }
print ( "The original dictionary : " + str (test_dict))
res = 'gfg' in test_dict and test_dict[ 'gfg' ] is not None
print ( "Does gfg have a Non-None value? : " + str (res))
|
Output
The original dictionary : {'gfg': None, 'is': 4, 'for': 2, 'CS': 10}
Does gfg have a Non-None value? : False
Time complexity: O(1)
Auxiliary space: O(1)
Similar Reads
Python | Check for None values in given dictionary
Many times, while working with dictionaries, we wish to check for a non-null dictionary, i.e check for None values in given dictionary. This finds application in Machine Learning in which we have to feed data with no none values. Let's discuss certain ways in which this task can be performed. Method
7 min read
Python - Check for Key in Dictionary Value list
Sometimes, while working with data, we might have a problem we receive a dictionary whose whole key has list of dictionaries as value. In this scenario, we might need to find if a particular key exists in that. Let's discuss certain ways in which this task can be performed. Method #1: Using any() Th
6 min read
Check if Value Exists in Python Dictionary
Dictionaries in Python offer a powerful way to store and retrieve data through key-value pairs. As developers, frequently, we encounter scenarios where we need to determine whether a specific value exists within a dictionary. In this article, we will explore commonly used methods to perform this tas
4 min read
Check if Json Object has Empty Value in Python
We have JSON data and we need to check if the JSON Object has an empty value or not in Python. In this article, we will see some methods that help us to check if JSON objects have empty values or not in Python. Example Input : '{"name": "John", "age": 25, "city": ""}'Output : Empty Value Found for K
3 min read
Python - Check if all values are K in dictionary
While working with dictionary, we might come to a problem in which we require to ensure that all the values are K in dictionary. This kind of problem can occur while checking the status of the start or checking for a bug/action that could have occurred. Letâs discuss certain ways in which this task
9 min read
Check if one dictionary is subset of other - Python
Checking if one dictionary is a subset of another involves verifying whether all key-value pairs of the smaller dictionary exist in the larger dictionary with the same values. For example, given two dictionaries a = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5} and b = {'gfg': 1, 'is': 2, 'best'
4 min read
Python - Count if dictionary position equals key or value
Given a dictionary, count instances where dictionary item position equals key or value. Valid for Py >= 3.6 [ Introduction of dictionary ordering ]. Input : test_dict = {5:3, 2:3, 10:4, 7:3, 8:1, 9:5} Output : 2 Explanation : At 3 and 5th position, values are 3 and 5. Input : test_dict = {5:3, 2:
3 min read
Check if a Key Exists in a Python Dictionary
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 ge
4 min read
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
Python | Sum values for each key in nested dictionary
Given a nested dictionary and we have to find sum of particular value in that nested dictionary. This is basically useful in cases where we are given a JSON object or we have scraped a particular page and we want to sum the value of a particular attribute in objects. Code #1: Find sum of sharpness v
2 min read