Filter Non-None dictionary keys in Python


Python dictionary is one of the most popular data types among the following 4 datatypes. The dictionary defines the key with value pair and doesn’t allow the duplicate. The values are either strings or integers. Sometimes, while working on the dictionary it has some empty values that the None value can fill. For example- when we are working on a machine learning dataset it has found that some of the rows are empty and can be filled by the value None when performing the particular task. In Python, we have some built-in functions like items() and lambda that can be used to Filter Non-None dictionary keys in Python.

Let’s take an example of this −

The given dictionary, {‘A’: 11, ‘B’: None, ‘C’: 29, ‘D’: None}
Then the final result becomes {‘A’: 11, ‘C’: 29}

Syntax

The following syntax is used in the examples −

items()

The items() is a built-in method in Python that allows it to iterate through both keys and values in the dictionary.

lambda

The function lambda offers a shortcut for declaring brief anonymous functions using the lambda keyword. The lambda functions behave when declared with the def keyword.

Using Dictionary Comprehension

The program sets the key and value to transform one dictionary into another by using dictionary comprehension. Then use the built-in function named items() and conditional if-statement to filter the None values from the list.

Example

In the following example, it will use the dictionary comprehension that creates a new dictionary. In the function return statement, it iterates over the key-value pairs in the dictionary using the items() method. Then check for each key-value pair, if the value is not None, then key-value pair is included in the new dictionary. Then create the original dictionary to sets its value. Next, use the calling function to call the function and it is called as recursion and store it in the variable filtered_dict. Finally, we are printing the result with the help of variable filtered_dict.

def filter_none(dictionary):
   return {key: value for key, value in dictionary.items() if value is not None}
# Create the dictionary
my_dict = {'a': 10, 'b': None, 'c': 30, 'd': None, 'e': 50}
filtered_dict = filter_none(my_dict)
print("After filter of Non-none dictionary key:\n", filtered_dict)

Output

 After filter of Non-none dictionary key:
 {'a': 10, 'c': 30, 'e': 50}

Using Filter() Function

The program uses the filter() function which accepts two parameters as built-in functions that are- lambda and items() to filter the Non-None dictionary keys in Python.

Example

In the following example, we will show the built-in function named filter() along with lambda to remove the value from the dictionary. In general, this returning function acts as a list comprehension. Then it will create the input dictionary to set the none values and next it will use the calling function to pass the input dictionary and get the result.

def filter_non_none_dict_filter(dictionary):
   return dict(filter(lambda item: item[1] is not None, dictionary.items()))

my_dict = {'I': 100, 'II': None, 'III': 300, 'IV': None, 'V': None}
filtered_dict = filter_non_none_dict_filter(my_dict)
print("After the filter of Non-none dictionary key:\n", filtered_dict)

Output

 After the filter of Non-none dictionary key:
 {'I': 100, 'III': 300}

Using a for Loop and Dictionary

The program uses the for loop to iterate into the key and value of dictionary items and also uses the if-statement to check the condition based on None and that will filter Non-None dictionary keys in Python.

Example

In the following example, start the program with a function named filter_dict_loop that accepts the parameter named dictionary to receive its value. Then create the empty dictionary in the variable filter_dict that will store only integer value of the key. Now use the for loop that iterates the key and value of the dictionary using method items(). Using an if-statement it will check if the value is found to be none then it will auto-removing the key : value from the dictionary. Next, return the function. Moving ahead to create the dictionary that includes a combination of integers and none values in the key and store it in the variable my_dict. The function call is used to call the function to pass the parameter as a variable named f_dict. Finally, we are printing the result with the help of variable f_dict.

def filter_dict_loop(dictionary):
   filtered_dict = {}
   for key, value in dictionary.items():
      if value is not None:
         filtered_dict[key] = value
   return filtered_dict
# Create the dictionary 
my_dict = {'A': 91, 'B': None, 'C': 33, 'D': 78, 'E': 5}
f_dict = filter_dict_loop(my_dict)
print("After the filter of Non-none dictionary key:\n", f_dict)

Output

After the filter of Non-none dictionary key:
 {'A': 91, 'C': 33, 'D': 78, 'E': 5}

Using Dictionary Comprehension With a Conditional Ternary Expression

The program uses dictionary comprehension that transforms the original dictionary into the filtered dictionary and conditional ternary expression is a way to write an if-else statement in one line. It’s often used in dictionary comprehensions to conditionally include key-value pairs.

Example

In the following example, begin the program by defining a recursive function named filter_dict_conditional that accepts the dictionary parameter to access all its key and value element. Then it returns the function by removing the non-None dictionary key. Next, it will create the dictionary to set the key along with its value and store it in the variable my_dict. Now use the calling function to pass the parameter as a variable named my_dict and store it in the variable filtered_dict. Finally, print the result with the help of variable filtered_dict.

def filter_dict_conditional(dictionary):
   return {key: value for key, value in dictionary.items() if value if not None}

my_dict = {'ABC': 11, 'DEF': None, 'GHI': 13, 'JKL': None, 'MNO': 15}
filtered_dict = filter_dict_conditional(my_dict)
print("After the filter of Non-none dictionary key:\n", filtered_dict)

Output

 After the filter of Non-none dictionary key:
 {'ABC': 11, 'GHI': 13, 'MNO': 15}

Conclusion

We discussed the various method to understand the filter of Non-None dictionary keys in Python. The various built-in method like items(), lambda, and filter() can be used to remove the Non-none value. This program relates the real-life example of a machine learning dataset while filling the empty data value to none by giving specific conditions based on the dictionary.

Updated on: 17-Jul-2023

147 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements