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
# Python3 code to demonstrate working of
# Check if key has Non-None value in dictionary
# Using if
# Initialize dictionary
test_dict = {'gfg': None, 'is': 4, 'for': 2, 'CS': 10}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Using if
# Check if key has Non-None value in dictionary
res = False
if test_dict['gfg']:
res = True
# printing result
print("Does gfg have a Non-None value? : " + str(res))
OutputThe 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
# Python3 code to demonstrate working of
# Check if key has Non-None value in dictionary
# Using bool() + get()
# Initialize dictionary
test_dict = {'gfg': None, 'is': 4, 'for': 2, 'CS': 10}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Using bool() + get()
# Check if key has Non-None value in dictionary
res = bool(test_dict.get('gfg'))
# printing result
print("Does gfg have a Non-None value? : " + str(res))
OutputThe 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
# Python3 code to demonstrate working of
# Check if key has Non-None value in dictionary
# Using ternary operator
# Initialize dictionary
test_dict = {'gfg' : None, 'is' : 4, 'for' : 2, 'CS' : 10}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Using ternary operator
# Check if key has Non-None value in dictionary
res = True if 'gfg' in test_dict and test_dict['gfg'] is not None else False
# printing result
print("Does gfg have a Non-None value? : " + str(res))
OutputThe 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
# Python3 code to demonstrate working of
# Check if key has Non-None value in dictionary
# Using try-except block
# Initialize dictionary
test_dict = {'gfg': None, 'is': 4, 'for': 2, 'CS': 10}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Using try-except block
# Check if key has Non-None value in dictionary
try:
if test_dict['gfg'] is not None:
res = True
else:
res = False
except KeyError:
res = False
# printing result
print("Does gfg have a Non-None value? : " + str(res))
OutputThe 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
# Python3 code to demonstrate working of
# Check if key has Non-None value in dictionary
# Using dictionary's get() method with default value
# Initialize dictionary
test_dict = {'gfg' : None, 'is' : 4, 'for' : 2, 'CS' : 10}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Using dictionary's get() method with default value
# Check if key has Non-None value in dictionary
res = True if test_dict.get('gfg', None) is not None else False
# printing result
print("Does gfg have a Non-None value? : " + str(res))
OutputThe 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
# Initialize dictionary
test_dict = {'gfg': None, 'is': 4, 'for': 2, 'CS': 10}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Using the "in" keyword with a direct comparison to None value
# Check if key has Non-None value in dictionary
res = 'gfg' in test_dict and test_dict['gfg'] is not None
# printing result
print("Does gfg have a Non-None value? : " + str(res))
OutputThe 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
We are given a dictionary and our task is to check whether a specific value exists in it or not. For example, if we have d = {'a': 1, 'b': 2, 'c': 3} and we want to check if the value 2 exists, the output should be True. Let's explore different ways to perform this check in Python.Naive ApproachThis
2 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'
3 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 get
4 min read
Python - Filter Non-None dictionary Keys
Many times, while working with dictionaries, we wish to get keys for a non-null keys. 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 #1 : Using loop In this we just run a loop for al
6 min read
Python | Check if Non-None values are contiguous
Sometimes, while working with Python lists, we can have a problem in which we need to find if all the values that are valid (Non None). This has a lot of application in day-day programming. Let's discuss a method in which this task can be performed. Method 1: Using iterator + all() + any() Combinati
6 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