Python | Filter the negative values from given dictionary
Given a dictionary, the task is to filter all the negative values from given dictionary. Let’s discuss few methods to do this task.
Method #1: Using dict comprehension
Follow the below steps to implement:
- Initializing a dictionary named ini_dict with some key-value pairs.
- Print the initial dictionary using the print() function.
- Next, create a new dictionary named result using dictionary comprehension. Dictionary comprehension is a concise way to create dictionaries from other iterables like lists, tuples, and sets.
- In the dictionary comprehension, iterate over the key-value pairs of the ini_dict using the items() method.
- For each key-value pair, check if the value is greater than or equal to 0 using the if condition.
- If the condition is true, add the key-value pair to the new dictionary result.
- Finally, print the filtered dictionary result using the print() function.
Below is the implementation of the above approach:
Python3
# Python code to demonstrate # return the filtered dictionary # on certain criteria # Initialising dictionary ini_dict = { 'a' : 1 , 'b' : - 2 , 'c' : - 3 , 'd' : 7 , 'e' : 0 } # printing initial dictionary print ( "initial lists" , str (ini_dict)) # filter dictionary such that no value is greater than 0 result = dict ((k, v) for k, v in ini_dict.items() if v > = 0 ) print ( "resultant dictionary : " , str (result)) |
initial lists {'a': 1, 'b': -2, 'c': -3, 'd': 7, 'e': 0} resultant dictionary : {'a': 1, 'd': 7, 'e': 0}
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #2: Using lambda and filter
Python3
# Python code to demonstrate # return the filtered dictionary # on certain criteria # Initialising dictionary ini_dict = { 'a' : 1 , 'b' : - 2 , 'c' : - 3 , 'd' : 7 , 'e' : 0 } # printing initial dictionary print ( "initial lists" , str (ini_dict)) # filter dictionary such that no value is greater than 0 result = dict ( filter ( lambda x: x[ 1 ] > = 0.0 , ini_dict.items())) result = dict (result) print ( "resultant dictionary : " , str (result)) |
initial lists {'a': 1, 'b': -2, 'c': -3, 'd': 7, 'e': 0} resultant dictionary : {'a': 1, 'd': 7, 'e': 0}
Time Complexity: O(n) where n is the number of elements in the dictionary.
Auxiliary Space: O(n) as the size of the resultant dictionary can be equal to the number of elements in the initial dictionary.
Method #3 : Using find() method
Python3
# Python code to demonstrate # return the filtered dictionary # on certain criteria # Initialising dictionary ini_dict = { 'a' : 1 , 'b' : - 2 , 'c' : - 3 , 'd' : 7 , 'e' : 0 } # printing initial dictionary print ( "initial lists" , str (ini_dict)) # filter dictionary such that no value is greater than 0 res = dict () for i in ini_dict: if ( str (ini_dict[i]).find( "-" ) ! = 0 ): res[i] = ini_dict[i] print ( "resultant dictionary : " , str (res)) |
initial lists {'a': 1, 'b': -2, 'c': -3, 'd': 7, 'e': 0} resultant dictionary : {'a': 1, 'd': 7, 'e': 0}
The time complexity of this code is O(n), where n is the number of items in the initial dictionary ini_dict.
The auxiliary space used by this code is O(n).
Method #4 : Using map() and a custom function
Here is an example of using map() and a custom function to filter negative values from a dictionary:
Python3
#If the value is negative, it returns None. def filter_negative(item): key, value = item if value < 0 : return return (key, value) #Initialize the dictionary ini_dict = { 'a' : 1 , 'b' : - 2 , 'c' : - 3 , 'd' : 7 , 'e' : 0 } #Use map to apply the filter_negative function to each item in the dictionary and return a map object #Use filter to remove the None values from the map object #Use dict to convert the map object to a dictionary result = dict ( filter ( None , map (filter_negative, ini_dict.items()))) #Print the resulting dictionary print (result) #This code is contributed by Edula Vinay Kumar Reddy |
{'a': 1, 'd': 7, 'e': 0}
The filter_negative() function takes a tuple representing a key-value pair in the dictionary, and returns the tuple if the value is non-negative. If the value is negative, the function returns None, which is filtered out by the filter() function. The map() function applies filter_negative() to each item in the dictionary, producing a list of tuples. The filter() function then filters out any None values, and the resulting list is passed to dict() to create the final filtered dictionary.
Time complexity: O(n), where n is the number of items in the dictionary. T
Auxiliary Space: O(n), as the filtered dictionary will have a size equal to the number of non-negative values in the original dictionary.
Method #5 : Using startswith() method
Python3
# Python code to demonstrate # return the filtered dictionary # on certain criteria # Initialising dictionary ini_dict = { 'a' : 1 , 'b' : - 2 , 'c' : - 3 , 'd' : 7 , 'e' : 0 } # printing initial dictionary print ( "initial lists" , str (ini_dict)) # filter dictionary such that no value is greater than 0 res = dict () for i in list (ini_dict.keys()): x = str (ini_dict[i]) if ( not x.startswith( "-" )): res[i] = ini_dict[i] print ( "resultant dictionary : " , str (res)) |
initial lists {'a': 1, 'b': -2, 'c': -3, 'd': 7, 'e': 0} resultant dictionary : {'a': 1, 'd': 7, 'e': 0}
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #6: Using list comprehension and dict() constructor
Step-by-step approach:
- Initialize the dictionary ini_dict
- Print the initial dictionary ini_dict
- Use a list comprehension to filter the dictionary such that no value is greater than 0. Store the resulting key-value pairs as a list of tuples.
- Convert the list of tuples into a dictionary using the dict() constructor.
- Print the resultant dictionary result.
- Compute the time complexity and auxiliary space complexity.
Below is the implementation of the above approach:
Python3
# Python code to demonstrate # return the filtered dictionary # on certain criteria # Initialising dictionary ini_dict = { 'a' : 1 , 'b' : - 2 , 'c' : - 3 , 'd' : 7 , 'e' : 0 } # printing initial dictionary print ( "initial dictionary:" , ini_dict) # using list comprehension and dict() constructor result = dict ([(k, v) for k, v in ini_dict.items() if v > = 0 ]) # printing resultant dictionary print ( "resultant dictionary:" , result) # compute time complexity and auxiliary space # time complexity: O(N) # auxiliary space: O(N) |
initial dictionary: {'a': 1, 'b': -2, 'c': -3, 'd': 7, 'e': 0} resultant dictionary: {'a': 1, 'd': 7, 'e': 0}
Time complexity: O(N) where N is the number of key-value pairs in the initial dictionary.
Auxiliary space: O(N) because we’re creating a new list of tuples to store the filtered key-value pairs before converting it into a dictionary.
Please Login to comment...