Python | Filter the negative values from given dictionary
Last Updated :
23 Mar, 2023
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))
Outputinitial 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))
Outputinitial 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))
Outputinitial 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
Output{'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))
Outputinitial 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)
Outputinitial 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.
Similar Reads
Even Values Update in Dictionary - Python The task of updating even values in a dictionary in Python involves modifying the values associated with specific keys based on a condition, typically checking whether the values are even. For example, consider a dictionary like d = {'gfg': 6, 'is': 4, 'best': 7}. The goal is to update the values by
3 min read
Python - Filter odd elements from value lists in dictionary Sometimes, while working with Python dictionaries we can have problem in which we need to perform the removal of odd elements from values list of dictionaries. This can have application in many domains including web development. Lets discuss certain ways in which this task can be performed. Method
6 min read
Python | Test if element is dictionary value Sometimes, while working with a Python dictionary, we have a specific use case in which we just need to find if a particular value is present in the dictionary as it's any key's value. This can have use cases in any field of programming one can think of. Let's discuss certain ways in which this prob
4 min read
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
Dictionary items in value range in Python In this article, we will explore different methods to extract dictionary items within a specific value range. The simplest approach involves using a loop.Using LoopThe idea is to iterate through dictionary using loop (for loop) and check each value against the given range and storing matching items
2 min read
Python - Filter dictionaries by values in Kth Key in list Given a list of dictionaries, the task is to write a Python program to filter dictionaries on basis of elements of Kth key in the list. Examples: Input : test_list = [{"Gfg" : 3, "is" : 5, "best" : 10}, {"Gfg" : 5, "is" : 1, "best" : 1}, {"Gfg" : 8, "is" : 3, "best" : 9}, {"Gfg" : 9, "is" : 9, "best
9 min read
Python - Test for Empty Dictionary Value List Given a dictionary with list as values, check if all lists are empty. Input : {"Gfg" : [], "Best" : []} Output : True Explanation : Both lists have no elements, hence True. Input : {"Gfg" : [], "Best" : [4]} Output : False Explanation : "Best" contains element, Hence False. Method #1 : Using any() +
6 min read
Python Remove Item from Dictionary by Value We are given a dictionary and our task is to remove key-value pairs where the value matches a specified target. This can be done using various approaches, such as dictionary comprehension or iterating through the dictionary. For example: d = {"a": 10, "b": 20, "c": 10, "d": 30} and we have to remove
3 min read
Python - Filter dictionary values in heterogeneous dictionary Sometimes, while working with Python dictionaries, we can have a problem in which we need to filter out certain values based on certain conditions on a particular type, e.g all values smaller than K. This task becomes complex when dictionary values can be heterogeneous. This kind of problem can have
6 min read
Filter Dictionary Key based on the Values in Selective List - Python We are given a dictionary where each key is associated with a value and our task is to filter the dictionary based on a selective list of values. We want to retain only those key-value pairs where the value is present in the list. For example, we have the following dictionary and list: d = {'apple':
3 min read