Python - Filter Non-None dictionary Keys
Last Updated :
11 May, 2023
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 all the keys and check for values, if its not None, we append into a list which stores keys of all Non None keys.
Python3
# Python3 code to demonstrate working of
# Non-None dictionary Keys
# Using loop
# initializing dictionary
test_dict = {'Gfg' : 1, 'for' : 2, 'CS' : None}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Using loop
# Non-None dictionary Keys
res = []
for ele in test_dict:
if test_dict[ele] is not None :
res.append(ele)
# printing result
print("Non-None keys list : " + str(res))
OutputThe original dictionary is : {'Gfg': 1, 'for': 2, 'CS': None}
Non-None keys list : ['Gfg', 'for']
Time Complexity: O(n*n) where n is the number of elements in the string list. The loop is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the test list.
Method #2 : Using dictionary comprehension This task can also be performed using dictionary comprehension. In this, we perform similar operation as above method, just as a shorthand.
Python3
# Python3 code to demonstrate working of
# Non-None dictionary Keys
# Using dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 1, 'for' : 2, 'CS' : None}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Non-None dictionary Keys
# Using dictionary comprehension
res = list({ele for ele in test_dict if test_dict[ele]})
# printing result
print("Non-None keys list : " + str(res))
OutputThe original dictionary is : {'Gfg': 1, 'for': 2, 'CS': None}
Non-None keys list : ['for', 'Gfg']
Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #3 : Using filter() and lambda function
Python3
# Python3 code to demonstrate working of
# Non-None dictionary Keys
# Using filter() and lambda function
# initializing dictionary
test_dict = {'Gfg' : 1, 'for' : 2, 'CS' : None}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Non-None dictionary Keys
# Using filter() and lambda function
res = list(filter(lambda x: test_dict[x] is not None, test_dict))
# printing result
print("Non-None keys list : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original dictionary is : {'Gfg': 1, 'for': 2, 'CS': None}
Non-None keys list : ['Gfg', 'for']
This approach is similar to the first one where we use a loop to iterate through the keys, but here we use the filter() function in combination with a lambda function to filter out the keys that have a non-None value.
Time complexity: O(n) - where n is the number of keys in the dictionary.
Auxiliary Space: O(n) - as we are creating a new list to store the non-None keys.
Method #4: using list comprehension
Python3
# initializing dictionary
test_dict = {'Gfg' : 1, 'for' : 2, 'CS' : None}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Using list comprehension
res = [key for key, value in test_dict.items() if value is not None]
# printing result
print("Non-None keys list : " + str(res))
#This code is contributed by Vinay Pinjala.
OutputThe original dictionary is : {'Gfg': 1, 'for': 2, 'CS': None}
Non-None keys list : ['Gfg', 'for']
Time Complexity:O(N)
Auxiliary Space :O(N)
Method 5: Using the map() function with a lambda function.
Step-by-step approach:
- Initialize the dictionary.
- Use map() function with a lambda function to map each key to itself if its value is not None, or to None otherwise.
- Use filter() function with a lambda function to filter out the None values from the mapped list.
- Convert the filtered list to a list using list() function.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Non-None dictionary Keys
# Using map() and filter()
# initializing dictionary
test_dict = {'Gfg' : 1, 'for' : 2, 'CS' : None}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Using map() and filter()
# Non-None dictionary Keys
res = list(filter(lambda x: x is not None, map(lambda x: x if test_dict[x] is not None else None, test_dict)))
# printing result
print("Non-None keys list : " + str(res))
OutputThe original dictionary is : {'Gfg': 1, 'for': 2, 'CS': None}
Non-None keys list : ['Gfg', 'for']
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the filtered list.
Method 6: Using Recursion method:
- Define a recursive function non_none_keys that takes a dictionary as input.
- Check if the dictionary is empty. If so, return an empty list.
- If the dictionary is not empty, pop an item from the dictionary.
- Recursively call non_none_keys on the remaining dictionary and store the result in a variable res
- Check if the value of the popped item is not None. If so, append the key to res.
- Return res.
- Initialize a dictionary test_dict.
- Print the original dictionary.
- Call non_none_keys on a copy of the dictionary and store the result in res.
- Print the resulting list.
Python3
def non_none_keys(dictionary):
if not dictionary:
return []
key, value = dictionary.popitem()
res = non_none_keys(dictionary)
if value is not None:
res.append(key)
return res
test_dict = {'Gfg': 1, 'for': 2, 'CS': None}
print("The original dictionary is : " + str(test_dict))
res = non_none_keys(test_dict.copy())
print("Non-None keys list : " + str(res))
#This code is contributed by Jyothi Pinjala
OutputThe original dictionary is : {'Gfg': 1, 'for': 2, 'CS': None}
Non-None keys list : ['Gfg', 'for']
Time complexity: O(n), where n is the number of items in the dictionary.
Space complexity: O(n), due to the recursive calls and the storage of the resulting list.
Similar Reads
Python | Filter Tuple Dictionary Keys
Sometimes, while working with Python dictionaries, we can have itâs keys in form of tuples. A tuple can have many elements in it and sometimes, it can be essential to get them. If they are a part of a dictionary keys and we desire to get filtered tuple key elements, we need to perform certain functi
4 min read
Python - Maximum of filtered Keys in dictionary
Sometimes while working with Python dictionaries, we might have a problem in which we require to just maximum the selective key values from the dictionary. This problem can occur in web development domain. Letâs discuss certain ways in which this problem can be solved. Method #1: Using list comprehe
6 min read
Filter List of Python Dictionaries by Key in Python
In Python, filtering a list of dictionaries based on a specific key is a common task when working with structured data. In this article, weâll explore different ways to filter a list of dictionaries by key from the most efficient to the least.Using List Comprehension List comprehension is a concise
3 min read
Python | Check if key has Non-None value in dictionary
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 th
6 min read
Get Next Key in Dictionary - Python
We are given a dictionary and need to find the next key after a given key, this can be useful when iterating over dictionaries or accessing elements in a specific order. For example, consider the dictionary: data = {"a": 1, "b": 2, "c": 3, "d": 4} if the current key is "b" then the next key should b
2 min read
Filter List Of Dictionaries in Python
Filtering a list of dictionaries is a fundamental programming task that involves selecting specific elements from a collection of dictionaries based on defined criteria. This process is commonly used for data manipulation and extraction, allowing developers to efficiently work with structured data b
2 min read
Key Index in Dictionary - Python
We are given a dictionary and a specific key, our task is to find the index of this key when the dictionaryâs keys are considered in order. For example, in {'a': 10, 'b': 20, 'c': 30}, the index of 'b' is 1.Using dictionary comprehension and get()This method builds a dictionary using dictionary comp
2 min read
Python Iterate Dictionary Key, Value
In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
3 min read
Get first K items in dictionary = Python
We are given a dictionary and a number K, our task is to extract the first K key-value pairs. This can be useful when working with large dictionaries where only a subset of elements is needed. For example, if we have: d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} and K = 2 then the expected output would be:
2 min read
Get the First Key in Dictionary - Python
We are given a dictionary and our task is to find the first key in the dictionary. Since dictionaries in Python 3.7+ maintain insertion order, the first key is the one that was added first to the dictionary. For example, if we have the dictionary {'a': 10, 'b': 20, 'c': 30}, the first key is 'a'.Usi
2 min read