Python - Filter the negative values from given dictionary

PythonServer Side ProgrammingProgramming

As part of data analysis, we will come across scenarios to remove the negative values form a dictionary. For this we have to loop through each of the elements in the dictionary and use a condition to check the value. Below two approaches can be implemented to achieve this.

Using for loop

W simply loop through the elements of the list using a for loop. In every iteration we use the items function to compare the value of the element with the 0 for checking negative value.

Example

 Live Demo

dict_1 = {'x':10, 'y':20, 'z':-30, 'p':-0.5, 'q':50}

print ("Given Dictionary :", str(dict_1))

final_res_1 = dict((i, j) for i, j in dict_1.items() if j >= 0)

print("After filtering the negative values from dictionary : ", str(final_res_1))

Output

Running the above code gives us the following result:

Given Dictionary : {'x': 10, 'y': 20, 'z': -30, 'p': -0.5, 'q': 50}
After filtering the negative values from dictionary : {'x': 10, 'y': 20, 'q': 50}

Using lambda function

We use a lambda function for a shorter and clearer syntax. In this case we implement the same logic as above but use a lambda function instead.

Example

 Live Demo

dictA = {'x':-4/2, 'y':15, 'z':-7.5, 'p':-9, 'q':17.2}

print ("\nGiven Dictionary :", dictA)

final_res = dict(filter(lambda k: k[1] >= 0.0, dictA.items()))

print("After filtering the negative values from dictionary : ", str(final_res))

Output

Running the above code gives us the following result:

Given Dictionary : {'x': -2.0, 'y': 15, 'z': -7.5, 'p': -9, 'q': 17.2}
After filtering the negative values from dictionary : {'y': 15, 'q': 17.2}
raja
Published on 07-Jan-2020 06:48:05
Advertisements